javascript previousSiblingで前にあるノードを取得する

javascript previousSiblingで前にあるノードを取得する

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

環境

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

previousSibling使い方

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

ノード.previousSibling

previousSibling使い方

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

<script>

'use strict';

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

console.log(node.previousSibling)

</script>

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

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

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

<script>

'use strict';

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

console.log(node.previousSibling)

</script>

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

複数のノード

複数のノードを指定する場合、例えば「getElementsByClassName」だと「v.previousSibling」などを使用します。

<p></p><div class="main">text</div>
<p></p><div class="main">text</div>
<p></p><div class="main">text</div>
<p></p><div class="main">text</div>
<p></p><div class="main">text</div>


<script>

'use strict';

const elm = document.getElementsByClassName("main");

if (0 < elm.length) {
    [...elm].forEach(function(v){ console.log( v.previousSibling )})
}

</script>

実行結果

存在しないノードを指定

存在しないノードを指定するとエラーが発生します。

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

<script>

'use strict';

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

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

</script>

エラーを防ぐには存在チェックをします。

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

<script>

'use strict';

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

if( node !== null) console.log(node.previousSibling)

</script>

コードの簡潔化

また、以下のコードを、

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

console.log(node.previousSibling)

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

console.log(main.previousSibling)

サンプルコード

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

※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.previousSibling.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>

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