楽天ポイント4倍セール!セール会場へ

Illustratorスクリプト(jsx)│子レイヤーはそのままで親レイヤーだけ削除する

最上位の親レイヤーを1つだけ対象にし、直下の子レイヤーを同じ位置の最上位へ移してから、空になった親を削除するJSXです。孫以下の階層は子と一緒に残します。

2026年10月3日にコードと説明を改修しました。

2026年10月20日に、その改修版でどの文書でも処理が止まっていた条件を1か所直しました。

直したコードは、Illustrator 2026(30.8.2)とWindows 11 Proで、[ファイル]→[スクリプト]→[その他のスクリプト…]から実行して確かめています。

掲載例はコピーしたデータで試し、レイヤー構造、重なり順、外観、書き出し結果を確認してから使ってください。

目次

この処理が対象にする構造

実行前実行後
親 → 子A → 孫A、親 → 子B子A → 孫A、子B。親だけ削除。
親の直下に図形・文字などがある削除せず、移動前に停止。
他の親レイヤー処理対象外。
ロック・非表示の親または子孫状態を変更せず停止。

親レイヤーに設定した透明度、描画モード、マスク、効果は、子を外すと見た目が変わる可能性があります。このコードは、それらを子に複製したり完全に検出したりする処理を持ちません。親の外観が必要なデータでは使わず、手動で構造を整理します。

スポンサーリンク

旧コードで削除され得た内容

以前のコードは全レイヤーを巡回してロックと表示状態を変更し、最初のレイヤーを削除していました。子を移しても親の直下の図形・文字は残るため、親と一緒に削除される可能性がありました。2026年10月3日の改修では、アクティブな最上位1件だけを対象にし、直下のオブジェクトがあれば操作前に停止します。

実行手順

  1. AIを別名のコピーとして保存する。
  2. レイヤーパネルで対象の最上位親をアクティブにし、新しいオブジェクトの配置先がその親であることを確認する。子孫や複数レイヤーの選択とは区別します。
  3. 親の直下に図形や文字がないこと、親の外観に依存していないことを確認する。
  4. 下のJSXを実行し、確認画面の親名と子の件数を照合する。
  5. 子・孫の階層、レイヤーの前後、オブジェクトの件数・外観を比較してから保存する。
(function () {
  try {
    if (app.documents.length === 0) throw new Error("ドキュメントを開いてください。");
    var doc = app.activeDocument;
    var parent = doc.activeLayer;
    if (parent.parent !== doc) throw new Error("最上位の親レイヤーをアクティブにしてください。");
    checkTree(parent);
    if (parent.layers.length === 0) throw new Error("子レイヤーがありません。");
    for (var i = 0; i < parent.pageItems.length; i++) {
      if (parent.pageItems[i].parent === parent)
        throw new Error("親の直下にオブジェクトがあります。削除せず終了します。");
    }
    var children = [];
    for (var j = 0; j < parent.layers.length; j++) children.push(parent.layers[j]);
    if (!confirm("コピーしたデータですか?\n親「" + parent.name + "」の子 " + children.length +
      " 件を最上位へ移し、親だけを削除します。\n親の外観・透明度が不要なことも確認してください。")) return;
    for (var k = 0; k < children.length; k++)
      children[k].move(parent, ElementPlacement.PLACEBEFORE);
    if (parent.layers.length !== 0 || parent.pageItems.length !== 0)
      throw new Error("親の中に項目が残っています。親は削除しません。");
    parent.remove();
    alert("親を削除しました。子の階層・重なり・外観を確認してから保存してください。");
  } catch (e) {
    alert(String(e) + "\n途中で失敗した場合、一部の移動が残る可能性があります。保存せず状態を確認してください。");
  }
  function checkTree(layer) {
    if (layer.locked || !layer.visible)
      throw new Error("ロック・非表示・編集不可のレイヤーがあります。");
    for (var i = 0; i < layer.layers.length; i++) checkTree(layer.layers[i]);
  }
}());

2026年10月20日に直した1行

10月3日の改修版では、ロックと非表示を調べる行に !layer.editable という条件も入っていました。

IllustratorのLayer(レイヤー)には editable というプロパティがなく、値は undefined になるため、この条件はいつも成り立ちます。

そのため、ロックも非表示もない文書でも、毎回「ロック・非表示・編集不可のレイヤーがあります。」と表示されて止まり、親は削除されませんでした。

上のコードは、その条件だけを外して if (layer.locked || !layer.visible) にしたものです。

ほかの行と、警告の文は変えていません。

JSXの保存と実行

コードをUTF-8のテキストで保存し、拡張子を.jsxにします。「ファイル」→「スクリプト」→「その他のスクリプト」から選びます。保存・実行の詳しい手順はJSX入門を参照してください。各コードは別々のファイルとして実行します。

Illustratorで実行した結果

2026年10月20日に、Illustrator 2026(30.8.2)、Windows 11 Pro(10.0.26200)で、練習用のファイルを作って確かめました。

レイヤーは上から「親」と「別の親」で、「親」の中に「子A」と「子B」、「子A」の中に「孫A」があり、どれもロック・非表示はありません。

練習用のファイルはスクリプトで作り、レイヤーの選択とコードの実行は画面で行いました。

レイヤーパネルで「親」の行を押し、[ファイル]→[スクリプト]→[その他のスクリプト…]で直したコードを選ぶと、親の名前と子の件数(2 件)が入った確認が出ました。

[はい]を押すと完了の表示が出て、レイヤーパネルは上から「子A」(中に「孫A」と青の円)、「子B」、「別の親」の順になりました。

子の順序と孫の階層は元のままで、親だけが消えました。

カンバスの見た目は変わらず、各レイヤーの図形の数も実行前と同じでした。

実行後に選ばれているレイヤーは「別の親」に変わっていました。

レイヤーパネルの実行前と実行後。実行前は親の中に子A(中に孫A)と子B、実行後は子A、子B、別の親の順で親だけがなくなっている
2026-10-20撮影。Adobe Illustrator 2026 (30.8.2)、Windows 11 Pro (10.0.26200)。左は「親」を選んだ実行前、右は直したコードを[ファイル]→[スクリプト]→[その他のスクリプト…]で実行した後のレイヤーパネル(拡大)。
スクリプト警告。コピーしたデータですか、親「親」の子 2 件を最上位へ移し親だけを削除します、という確認と、親を削除しました、という完了の表示
2026-10-20撮影。Adobe Illustrator 2026 (30.8.2)、Windows 11 Pro (10.0.26200)。直したコードを実行したときに出た確認(上)と、[はい]の後の完了の表示(下)。

止まる条件も画面で確かめた

「子B」をロックした文書、「孫A」を非表示にした文書、「親」の直下に四角を置いた文書でも、同じように「親」を選んで実行しました。

ロックと非表示の文書では「エラー: ロック・非表示・編集不可のレイヤーがあります。」と表示されました。

親の直下に四角がある文書では「エラー: 親の直下にオブジェクトがあります。削除せず終了します。」と表示されました。

どの場合も確認は出ず、[OK]で閉じた後のレイヤーの構造・ロック・表示は実行前と同じでした。

孫Aを非表示にした練習ファイルのレイヤーパネルと、エラー ロック・非表示・編集不可のレイヤーがあります、という警告
2026-10-20撮影。Adobe Illustrator 2026 (30.8.2)、Windows 11 Pro (10.0.26200)。孫Aを非表示にした文書で「親」を選んで実行したときの警告。[OK]の後もレイヤーは実行前のまま。

子のレイヤーを選んだまま実行した場合と、親の不透明度を50%にした場合は、画面ではなく、同じ処理をスクリプトから呼んで確かめました。

子を選んだときは「最上位の親レイヤーをアクティブにしてください。」で止まりました。

親の不透明度50%は子に引き継がれず、親を消した後の子は100%のままでした。

確かめていないこと

  • 親に描画モード・マスク・効果がある文書
  • 子や孫が多い文書、孫より深い階層がある文書
  • 移動の途中で失敗した場合の残り方
  • Mac版

上の項目は、今回の確認に含めていません。

途中で失敗した場合

moveが途中で失敗すると、すでに移動した子だけが最上位に出た状態が残ります。自動ロールバックや自動保存はしません。親の削除には最後まで進まず、残った親と移動済みの子を確認します。確実に元の構造へ戻すには、試験用コピーを保存せず閉じて開き直します。

移動前の子を配列へ控え、前から順に親の直前へ入れます。子の相対順序と孫の階層を保つことを意図した処理です。実機での順序・外観の比較は必要です。レイヤー取得・移動の基礎はレイヤー操作のJSXを参照してください。

参照資料

Adobeのレイヤー削除、Adobe資料をもとに維持されているLayerのAPI参照を参照しました。

スポンサーリンク

よくある質問:子レイヤーを残して親レイヤーを削除するJSX

このJSXは、何をするものですか?

最上位の親レイヤーを1つだけ対象にし、直下の子レイヤーを同じ位置の最上位へ移してから、空になった親を削除します。孫以下の階層は、子と一緒に残します。

どんな構造が対象で、どんな場合に止まりますか?

親 → 子A → 孫A、親 → 子B という構造なら、実行後は 子A → 孫A、子B になり、親だけが削除されます。親の直下に図形・文字などがある場合は、削除せず、移動前に停止します。ほかの親レイヤーは処理対象外で、ロック・非表示の親または子孫がある場合は、状態を変更せず停止します。

親レイヤーの透明度や効果は、どうなりますか?

親レイヤーに設定した透明度、描画モード、マスク、効果は、子を外すと見た目が変わる可能性があります。このコードは、それらを子に複製したり完全に検出したりする処理を持ちません。親の外観が必要なデータでは使わず、手動で構造を整理してください。

旧コードは、何が問題だったのですか?

以前のコードは、全レイヤーを巡回してロックと表示状態を変更し、最初のレイヤーを削除していました。子を移しても親の直下の図形・文字は残るため、親と一緒に削除される可能性がありました。2026年10月3日の改修では、アクティブな最上位1件だけを対象にし、直下のオブジェクトがあれば操作前に停止します。

実行するときの手順を教えてください。

AIを別名のコピーとして保存します。レイヤーパネルで対象の最上位親をアクティブにし、新しいオブジェクトの配置先がその親であることを確認します(子孫や複数レイヤーの選択とは区別します)。親の直下に図形や文字がないこと、親の外観に依存していないことを確認します。JSXを実行し、確認画面の親名と子の件数を照合します。子・孫の階層、レイヤーの前後、オブジェクトの件数・外観を比較してから保存します。

JSXは、どうやって保存・実行しますか?

コードをUTF-8のテキストで保存し、拡張子を.jsxにします。「ファイル」→「スクリプト」→「その他のスクリプト」から選びます。保存・実行の詳しい手順は、関連記事のJSX入門を参照してください。

途中で失敗したら、どうなりますか? 元に戻せますか?

moveが途中で失敗すると、すでに移動した子だけが最上位に出た状態が残ります。自動ロールバックや自動保存はしません。親の削除には最後まで進まず、残った親と移動済みの子を確認します。確実に元の構造へ戻すには、試験用コピーを保存せず閉じて開き直してください。

掲載コードは、実際のIllustratorで動作確認されていますか?

2026年10月3日の改修版には、どの文書でも処理が止まってしまう条件(!layer.editable)が入っていました。

2026年10月20日にその条件を外し、Illustrator 2026(30.8.2)とWindows 11 Proで画面から実行して確かめました。

親 → 子A → 孫A、親 → 子B の練習ファイルでは、子の順序と孫の階層を保ったまま親だけが削除されました。

ロック・非表示の子や、親の直下の図形があるときは、何も変えずに止まりました。

親に効果やマスクがある文書、子が多い文書、Mac版は確かめていません。

掲載例はコピーしたデータで試し、結果を確認してから使ってください。

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

コメント

コメント一覧 (60件)

  • Hey, you used to write excellent, but the last few posts have been kinda boring?K I miss your tremendous writings. Past several posts are just a bit out of track! come on!

  • Throughout this grand design of things you’ll secure an A for effort and hard work. Exactly where you actually lost everybody was first on all the facts. You know, people say, details make or break the argument.. And that couldn’t be more accurate at this point. Having said that, allow me tell you what exactly did work. The text is definitely pretty powerful which is most likely the reason why I am making the effort in order to comment. I do not make it a regular habit of doing that. Second, although I can see a leaps in reason you make, I am not necessarily convinced of exactly how you appear to unite the ideas which in turn make the actual conclusion. For the moment I shall subscribe to your position however wish in the foreseeable future you actually connect the dots better.

  • I really wanted to construct a simple note so as to appreciate you for those precious guides you are showing on this website. My extensive internet lookup has at the end of the day been honored with really good knowledge to share with my relatives. I would believe that most of us visitors are extremely fortunate to be in a decent site with so many outstanding professionals with very beneficial ideas. I feel extremely grateful to have encountered your entire website and look forward to some more cool minutes reading here. Thanks a lot once again for everything.

  • 경기도 안양출장마사지 셀럽의 코스와 가격, 자택·호텔 방문 상담, 선입금 없는 예약 및 현장 결제 기준을 확인하세요. 방문 가능 여부와 예상 도착 시간은 주소와 당일 일정에 따라 안내합니다.

  • 강릉출장안마로 장거리 출장이나 여행의 피로를 풀어보세요. 강릉 전 지역 어디든 찾아가는 전문 아로마 마사지·스포츠 마사지 서비스를 제공합니다. 비즈니스 출장객, 관광객, 강릉 지역 주민 모두 편리하게 이용할 수 있는 강릉출장안마 서비스입니다. 지금 문의하세요.

  • I’ve recently started a site, the information you offer on this web site has helped me tremendously. Thank you for all of your time & work.

  • 제주출장마사지 셀럽의 코스와 가격, 방문 예약 방법을 확인하세요. 제주시·서귀포시·애월·중문 등 지역별 상담과 숙소 출입, 예상 도착 시간, 제주출장안마 현장 결제 기준을 안내합니다.

  • What i do not realize is actually how you’re not really much more well-liked than you may be right now. You are so intelligent. You realize therefore considerably relating to this subject, made me personally consider it from so many varied angles. Its like women and men aren’t fascinated unless it is one thing to do with Lady gaga! Your own stuffs outstanding. Always maintain it up!

  • 포항출장마사지 전문 업체입니다. 24시간 연중무휴 운영과 100 후불제 시스템으로 언제든 편하게 예약 가능! 전원 한국여성 테라피스트가 커플마사지까지 전문 제공

  • Hiya, I’m really glad I’ve found this information. Today bloggers publish only about gossips and web and this is actually irritating. A good site with exciting content, this is what I need. Thank you for keeping this web site, I will be visiting it. Do you do newsletters? Cant find it.

  • Woah! I’m really enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s difficult to get that “perfect balance” between user friendliness and visual appeal. I must say that you’ve done a great job with this. Additionally, the blog loads extremely quick for me on Safari. Outstanding Blog!

  • An fascinating dialogue is worth comment. I feel that it’s best to write more on this subject, it might not be a taboo subject but generally people are not enough to speak on such topics. To the next. Cheers

  • I am curious to find out what blog system you are working with? I’m having some small security issues with my latest website and I’d like to find something more risk-free. Do you have any recommendations?

  • I really like your writing style, superb info, regards for putting up :D. “Faith is a continuation of reason.” by William Adams.

  • I’m extremely inspired with your writing talents as well as with the structure in your weblog. Is this a paid topic or did you modify it yourself? Either way stay up the nice quality writing, it is uncommon to look a nice weblog like this one these days..

  • It’s truly a nice and helpful piece of info. I am satisfied that you just shared this useful info with us. Please keep us up to date like this. Thanks for sharing.

  • Hello would you mind letting me know which webhost you’re using? I’ve loaded your blog in 3 different web browsers and I must say this blog loads a lot faster then most. Can you recommend a good hosting provider at a fair price? Thank you, I appreciate it!

  • Fantastic site. Lots of useful information here. I’m sending it to some friends ans also sharing in delicious. And obviously, thanks for your sweat!

  • Excellent read, I just passed this onto a friend who was doing a little research on that. And he just bought me lunch since I found it for him smile Thus let me rephrase that: Thank you for lunch!

  • Good post. I study something more difficult on totally different blogs everyday. It is going to at all times be stimulating to learn content from other writers and observe a little one thing from their store. I’d desire to make use of some with the content on my blog whether you don’t mind. Natually I’ll offer you a hyperlink on your internet blog. Thanks for sharing.

  • After study a few of the blog posts on your website now, and I truly like your way of blogging. I bookmarked it to my bookmark website list and will be checking back soon. Pls check out my web site as well and let me know what you think.

  • Some truly nice and utilitarian information on this internet site, also I conceive the style holds excellent features.

  • Have you ever considered about including a little bit more than just your articles? I mean, what you say is valuable and everything. But just imagine if you added some great photos or videos to give your posts more, “pop”! Your content is excellent but with images and video clips, this website could definitely be one of the best in its niche. Very good blog!

  • Hey very nice blog!! Man .. Beautiful .. Amazing .. I will bookmark your blog and take the feeds also…I am happy to find so many useful information here in the post, we need develop more techniques in this regard, thanks for sharing. . . . . .

  • Thanks for some other great post. The place else may anyone get that type of info in such an ideal manner of writing? I’ve a presentation subsequent week, and I’m on the look for such info.

  • wonderful points altogether, you just gained a brand new reader. What would you suggest about your post that you made some days ago? Any positive?

  • Attractive section of content. I just stumbled upon your site and in accession capital to assert that I acquire in fact enjoyed account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently rapidly.

  • 서울출장마사지 서울출장안마 셀럽은 고객이 머무는 장소에서 관리를 받을 수 있도록 방문 서비스를 안내합니다. 자택이나 숙소의 위치, 원하는 이용 시간, 코스를 알려주시면 예약 가능

  • 수원출장안마 셀럽의 출장마사지 코스와 가격, 선입금 없는 현장 결제 방식을 안내합니다. 영통·광교·인계동·권선동·장안구 등 방문 가능 지역과 예상 도착 시간

  • You really make it seem so easy with your presentation but I find this matter to be really something that I think I would never understand. It seems too complicated and very broad for me. I’m looking forward for your next post, I’ll try to get the hang of it!

  • Today, I went to the beach front with my children. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is completely off topic but I had to tell someone!

  • It’s really a great and useful piece of info. I am happy that you shared this helpful information with us. Please stay us up to date like this. Thank you for sharing.

  • Youre so cool! I dont suppose Ive learn anything like this before. So good to seek out somebody with some original thoughts on this subject. realy thank you for beginning this up. this website is one thing that’s needed on the internet, somebody with a little bit originality. useful job for bringing something new to the internet!

  • When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get four emails with the same comment. Is there any way you can remove me from that service? Thank you!

  • Terima kasih atas tulisan yang bagus. Pada kenyataannya ini sebelumnya adalah sebuah konten hiburan. Terlihat maju menjadi jauh lebih menyenangkan dari Anda! Namun, bagaimana kita dapat menjaga kontak?

  • 구미오피를 검색하며 구미 지역 일반 마사지·스파를 알아보는 분들을 위한 안내입니다. 프로그램 선택, 관리 시간과 비용, 시설·위생, 주차, 예약 전 확인사항과 자주 묻는 질문을 정리했습니다.

  • 밤토끼가 어떤 사이트였는지, 과거 이력과 현재 검색 정보를 구분하는 방법을 정리했습니다. 예전에 보던 웹툰 찾기, 공식 연재처 확인, 무료 회차와 대여·소장 차이, 자주 묻는 질문까지 한 번에 확인하세요.

  • 포항오피 검색어의 맥락과 온라인 정보 확인 기준을 정리했습니다. 광고성 표현과 후기의 출처, 게시물의 최신성, 개인정보 보호 방법, 포항 공공정보와 자주 묻는 질문을 확인하세요.

  • 親レイヤーだけを削除して子・孫の階層を保つ、という目的が明確で参考になりました。特に、旧コードが全レイヤーを巡回してロックや表示状態を変更し、直下の図形・文字まで消し得た点を明示しているのは安心材料です。2026年10月20日の修正で「どの文書でも止まっていた条件」を1か所直したとのことなので、修正前のコードを手元に残している場合は差し替えが必要だと理解しました。一方で、親の透明度・描画モード・マスク・効果は子へ複製されず見た目が変わり得るため、外観依存のデータでは手動整理が前提という注意は重要だと感じます。実行前に対象の最上位親をアクティブにし、直下にオブジェクトがないことを確認する手順も具体的で分かりやすいです。ただ、確認画面の親名と子の件数を照合する部分や、失敗時にどこまで戻せるのかの説明が本文だけではやや不足しているので、その点を補足してもらえると実務で使いやすくなりそうです。

  • Thanks , I’ve recently been searching for information about this topic for ages and yours is the greatest I’ve discovered so far. But, what about the conclusion? Are you sure about the source?

  • I want to point out my gratitude for your kind-heartedness for men who need help with in this matter. Your personal commitment to getting the message all around turned out to be quite effective and have without exception encouraged women much like me to achieve their pursuits. Your personal helpful help and advice implies much a person like me and even further to my mates. Best wishes; from everyone of us.

  • 소액결제현금화의 의미와 수수료 계산, 실제 부담액을 확인하세요. 휴대폰 결제 한도와 통신요금 청구, 관련 법령, 취소·환불 및 피해 대응까지 공식 자료를 바탕으로 정리했습니다.

  • Hi! I know this is kinda off topic but I was wondering which blog platform are you using for this website? I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform. I would be fantastic if you could point me in the direction of a good platform.

コメントする

目次