javascript lastChildで最後の子ノードを取得する
- 2021.03.14
- javascript
- javascript

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

今度はテキストノードを取得してみます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
/* html */ <div id="main"> <p id="one">one</p> <p id="two">two</p> text-node </div> /* javascript */ 'use strict'; const node = document.getElementById("main"); console.log(node.lastChild); |
実行結果をみると、親要素ノードからテキストノードが取得できていることが確認できます。

また、以下のコードを、
1 2 3 |
const node = document.getElementById("main"); console.log(node.lastChild); |
document.getElementByIdの省略を使用して、簡潔に記述することもできます。
1 |
console.log(main.lastChild); |
サンプルコード
以下は、
「変更」ボタンをクリックして、最後の子テキストノードを取得して変更するだけの
サンプルコードとなります。
※cssには「tailwind」を使用して、アロー関数で関数は定義してます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<!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.lastChild.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> |
最後のテキストノードが変更されていることが確認できます。

-
前の記事
CentOs7 FreeSFAを構築するまでの手順 2021.03.14
-
次の記事
React.js ライブラリ「react-autocomplete-input」を使ってシンプルなオートコンプリートを実装する 2021.03.14
コメントを書く