
ボタンを押したら、テーブルの行を追加するJavascriptを作成しています。下記のような流れになっています。
- ボタンをクリック
- addButton() を実行
- 新要素
actionElm
、親要素、挿入場所直前の要素を取得 - insertBefore の処理
- エラー
ボタンをクリックするとエラーが発生します。
test_js.html:73 Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.
新しいノードが挿入される前のノードは、このノードの子ではない。
Chromeの検証で追いかけてみると、親要素<table> actionTable
、親要素の中に子要素<tr> addButton
は確認できるので問題がなさそうに思えます。
エラーが発生するのは何が原因と考えられるでしょうか?
よろしくお願いします。
html
1<table class="table" id="actionTable"> 2 <tr> 3 <th scope="col" style="width:5%">列1</th> 4 <th scope="col" style="width:10%">列2</th> 5 <th scope="col" style="width:60%">列3</th> 6 <th scope="col" style="width:25%">列4</th> 7 </tr> 8 <tr> 9 <td> 10 <div> 11 <input type="checkbox" name="data[2][delete]"> 12 </div> 13 </td> 14 <td> 15 <input type="hidden" name="data[2][id]" value="7"> 16 <input type="text" name="data[2][name]" value="new4"> 17 </td> 18 <td><input type="text" name="data[2][url]" value="https://music.youtube.com"></td> 19 <td><input type="text" name="data[2][memo]" value="memoemoemo"></td> 20 </tr> 21 <tr> 22 <td> 23 <div> 24 <input type="checkbox" name="data[3][delete]"> 25 </div> 26 </td> 27 <td> 28 <input type="hidden" name="data[3][id]" value="8"> 29 <input type="text" name="data[3][name]" value="new3"> 30 </td> 31 <td><input type="text" name="data[3][url]" value="https://youtube.com"></td> 32 <td><input type="text" name="data[3][memo]" value="memoemoemo"></td> 33 </tr> 34 35 <tr id="addButton"> 36 <td colspan="4"> 37 <button type="button" onclick="addAction()">追加</button> 38 </td> 39 </tr> 40</table>
javascript
1<script> 2 function addAction() { 3 let actionElm = document.getElementById('actionTemplate').content.cloneNode(true); 4 let actionTable = document.getElementById('actionTable'); 5 let addButton = document.getElementById('addButton'); 6 actionTable.insertBefore(actionElm, addButton); 7 } 8</script>
html
1<template id="actionTemplate"> 2 <tr> 3 <td> 4 <div class="custom-control custom-checkbox"> 5 <input type="checkbox" name="data[-1][delete]"> 6 </div> 7 </td> 8 <td> 9 <input type="hidden" name="data[-1][id]" value="-1"> 10 <input type="text" name="data[-1][name]" value=""> 11 </td> 12 <td><input type="text" name="data[-1][text]" value=""></td> 13 <td><input type="text" name="data[-1][memo]" value=""></td> 14 </tr> 15</template>

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2022/05/24 11:50