javascript nextSiblingで次にあるノードを取得する

javascript nextSiblingで次にあるノードを取得する

javascriptで、nextSiblingを使用して、次にあるノードを取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 103.0.5060.134

nextSibling使い方

nextSiblingを使用すると、次にあるノードを取得することが可能です。
※ノードは、要素ノードだけでなく、改行を含んだテキストノードやコメントノードも存在します。

ノード.nextSibling

nextSiblings使い方

<!-- 改行のテキストノードを取得しないため改行はしない -->
<div id="main"></div><p></p>

<script>

'use strict';

const node = document.getElementById("main");

console.log(node.nextSibling)

</script>

実行結果を見ると、次のノードが取得されていることが確認できます。

今度は、改行を含んだノードを取得してみます。

<div id="main"></div>
<p></p>

<script>

'use strict';

const node = document.getElementById("main");

console.log(node.nextSibling)

</script>

実行結果をみると、改行を含んだテキストノードが次のノードとして取得できていることが確認できます。

また、nextSiblingは、次のノードを取得するので子ノードは取得はされません。

<div id="main"><div></div></div><p></p>

<script>

'use strict';

const node = document.getElementById("main");

console.log(node.nextSibling)

</script>

実行結果

また、以下のコードを、

const node = document.getElementById("main");

console.log(node.nextSibling)

document.getElementByIdの省略を使用して、簡潔に記述することもできます。

console.log(main.nextSibling)

次の要素が存在しない場合

次の要素が存在しない場合は「null」が返ります。

<body id="bd">

<script>

const node = document.getElementById("bd");

console.log(node.nextSibling) // null

</script>

</body>

要素が存在しない場合

指定した要素が存在しない場合は、エラーとなります。

<div id="main"></div>
<p></p>

<script>

'use strict';

const node = document.getElementById("noelm");

console.log(node.nextSibling)
// Uncaught TypeError: Cannot read properties of null (reading 'nextSibling')

</script>

なので、存在チェックしてから使用します。

const node = document.getElementById("noelm");

if(node !== null){

    console.log(node.nextSibling)
    
}

サンプルコード

以下は、
「変更」ボタンをクリックして、次にあるのテキストノードを取得して変更するだけの
サンプルコードとなります。

※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.nextSibling.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-green-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>

テキストノードが変更されていることが確認できます。