javascript childNodesで任意の子ノードを取得する
- 作成日 2021.02.23
- 更新日 2022.08.08
- javascript
- javascript

javascriptで、childNodesを使用して、任意の子ノードを取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。
環境
- OS windows10 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 103.0.5060.134
childNodes使い方
childNodesを使用すると、最後の子ノードを削除することが可能です。
※ノードは、要素ノードだけでなく、改行を含んだテキストノードやコメントノードも存在します。
親ノード.childNodes
childNodes使い方
<!-- 改行のテキストノードを取得しないため改行はしない -->
<div id="main"><p id="one">one</p><p id="two">two</p>text-node</div>
<script>
'use strict';
const node = document.getElementById("main");
console.log(node.childNodes.item(0));
console.log(node.childNodes.item(1));
console.log(node.childNodes.item(2));
</script>
実行結果を見ると、子ノードが1つずつ取得されていることが確認できます。

存在しないインデックス番号を指定した場合は「null」が返ります。
const node = document.getElementById("main");
console.log(node.childNodes.item(3)); // null
今度は、改行を含んだノードを取得してみます。
<div id="main">
<p id="one">one</p>
<p id="two">two</p>
text-node
</div>
<script>
'use strict';
const node = document.getElementById("main");
for (let i = 0; i < node.childNodes.length; ++i) {
console.log(node.childNodes.item(i));
}
</script>
実行結果をみると、改行を含んだテキストノードと要素ノードが取得できていることが確認できます。

存在しない要素を指定
存在しない要素を指定した場合は、エラーが発生します。
<div id="main">
<p id="one">one</p>
<p id="two">two</p>
text-node
</div>
<script>
'use strict';
const node = document.getElementById("main");
for (let i = 0; i < node.childNodes.length; ++i) {
console.log(node.childNodes.item(i));
}
</script>
存在チェックをしておくと、エラーは回避できます。
'use strict';
const node = document.getElementById("noelm");
if(node !== null){
for (let i = 0; i < node.childNodes.length; ++i) {
console.log(node.childNodes.item(i));
}
}
コードの短縮
また、以下のコードを、
const node = document.getElementById("main");
for (let i = 0; i < node.childNodes.length; ++i) {
console.log(node.childNodes.item(i));
}
document.getElementByIdの省略とforEachとアロー関数を使用して、簡潔に記述することもできます。
main.childNodes.forEach((v,i) => console.log(main.childNodes.item(i)))
サンプルコード
以下は、
「変更」ボタンをクリックして、最初と最後のテキストノードを取得して変更するだけの
サンプルコードとなります。
※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 = () => {
add.onclick = () => {
sample.childNodes.item(0).nodeValue = "変更します";
sample.childNodes.item(2).nodeValue = "変更します";
};
}
</script>
<body>
<div class="container mx-auto my-56 w-64 px-4">
<div id="sample" class="flex flex-col justify-center">
最初のテキストノード
<button id="add"
class="bg-gradient-to-r from-purple-400 to-blue-500 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>
テキストノードが変更されていることが確認できます。

-
前の記事
UVdeskをインストールして使用する 2021.02.23
-
次の記事
rails6 tiny_tdsインストール時にエラー「An error occurred while installing tiny_tds (2.1.3), and Bundler cannot continue.」が発生 2021.02.23
コメントを書く