javascript appendで最後の子ノードにノードを追加する
- 作成日 2021.02.18
- 更新日 2022.08.05
- javascript
- javascript

javascriptで、appendを使用して、最後の子ノードにノードを追加するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 103.0.5060.134
append使い方
appendを使用すると、最後の子ノードにノードを追加することが可能です。
ノード.append
append使い方
<div id="main">
<div id="one">one</div>
<div id="two">two</div>
</div>
<script>
'use strict';
const elm = document.getElementById("main");
const b = document.createElement("b");
const text = document.createTextNode("text");
b.appendChild(text);
elm.append(b);
</script>
実行結果を見ると、要素ノードが最後の子ノードに追加されているが確認できます。


存在しない要素を指定
存在しない要素を指定すると、エラーが発生します。
<div id="main">
<div id="one">one</div>
<div id="two">two</div>
</div>
<script>
'use strict';
const elm = document.getElementById("noelm");
const b = document.createElement("b");
const text = document.createTextNode("text");
b.appendChild(text);
elm.append(b);
// Uncaught TypeError: Cannot read properties of null (reading 'append')
</script>
存在チェックを行うと、エラーは防げます。
const elm = document.getElementById("noelm");
const b = document.createElement("b");
const text = document.createTextNode("text");
b.appendChild(text);
if(elm !== null) elm.append(b);
子要素が存在しない場合
子要素が存在しない場合は、要素内に生成されます。
<div id="main">
</div>
<script>
'use strict';
const elm = document.getElementById("main");
const b = document.createElement("b");
const text = document.createTextNode("text");
b.appendChild(text);
if(elm !== null) elm.append(b);
</script>
実行結果

コードの簡潔化
また、以下のコードを、
const elm = document.getElementById("main");
elm.append(b);
document.getElementByIdの省略を使用して、簡潔に記述することもできます。
main.append(b);
サンプルコード
以下は、
「追加」ボタンをクリックして、html要素を指定したノードの最後の子ノードに追加する
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>mebeeサンプル</title>
<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>
<script>
window.onload = () => {
btn.onclick = () => {
const b = document.createElement("b");
const text = document.createTextNode("text");
b.appendChild(text);
sample.append(b);
};
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
<button id="btn"
class="bg-gradient-to-r from-blue-500 to-purple-700 hover:from-pink-500 hover:to-yellow-500 text-white py-2 px-4 rounded-full mb-3 mt-4">
追加
</button>
</div>
</div>
</body>
</html>
要素ノードが追加されていることが確認できます。

-
前の記事
Apache エラー「Invalid command ‘RequestHeader’, perhaps misspelled or defined by a module not included in the server configuration」が発生した場合の対処法 2021.02.17
-
次の記事
Ruby 配列の値を削除する 2021.02.18
コメントを書く