javascript hasChildNodesで子ノードがあるかを判定する

javascript hasChildNodesで子ノードがあるかを判定する

javascriptで、hasChildNodesを使用して、子ノードがあるかを判定するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

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

hasChildNodes使い方

hasChildNodesを使用すると、子ノードがあるかを判定することが可能です。

ノード名.hasChildNodes()

// あれば true, なければ false

hasChildNodes使い方

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

<p id="result"></p>

<script>

'use strict';

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

if (node.hasChildNodes() === true) {
  document.getElementById("result").innerHTML = "yes";
}else{
  document.getElementById("result").innerHTML = "no";
}

</script>

実行結果をみると、対象のノードが子ノードをもっているのでtrueとなります。

逆に、以下のように子ノードを削除すると「false」となります。

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

<p id="result"></p>

<script>

'use strict';

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

if (node.hasChildNodes() === true) {
  document.getElementById("result").innerHTML = "yes";
}else{
  document.getElementById("result").innerHTML = "no";
}

</script>

実行結果

ただし、改行などがあるとテキストノードがあると判定されて「true」が返ります。

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

<p id="result"></p>

<script>

'use strict';

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

if (node.hasChildNodes() === true) {
  document.getElementById("result").innerHTML = "yes";
}else{
  document.getElementById("result").innerHTML = "no";
}

</script>

実行結果

また、以下のコードを、

document.getElementById('main').addEventListener('click',
  function(event) {
    event.target.parentNode.removeChild(this);
  }
)

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

(main.hasChildNodes() === true) ? result.innerHTML = "yes" : result.innerHTML = "no";

存在しないノードを指定

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

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

<p id="result"></p>

<script>

'use strict';

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

if (node.hasChildNodes() === true) {
  document.getElementById("result").innerHTML = "yes";
}else{
  document.getElementById("result").innerHTML = "no";
}
// // Uncaught TypeError: Cannot read properties of null (reading 'hasChildNodes')

</script>

なので、使用する前は指定したノードが存在するかをチェックする必要があります。

'use strict';

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

if(node !== null){

    if (node.hasChildNodes() === true) {
    document.getElementById("result").innerHTML = "yes";
    }else{
    document.getElementById("result").innerHTML = "no";
    }

}

サンプルコード

以下は、
「判定」ボタンをクリックして、子ノードが存在するかを判定するだけの
サンプルコードとなります。

※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.hasChildNodes() === true) ? add.innerHTML = "true" : add.innerHTML = "false";
    };

  }

</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>

判定結果が表示されていることが確認できます。