javascript firstChildで最初の子ノードを取得する

javascript firstChildで最初の子ノードを取得する

javascriptで、firstChildを使用して、最初の子ノードを取得するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

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

firstChild使い方

「firstChild」を使用すると、最初の子ノードを削除することが可能です。

親ノード.firstChild

firstChild使い方

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

<script>

'use strict';

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

console.log(node.firstChild);

</script>

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

今度はテキストノードを取得してみます。

<div id="main">
  text-node
  <p id="one">one</p>
  <p id="two">two</p>
</div>

<script>

'use strict';

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

console.log(node.firstChild);

</script>

実行結果をみると、親要素ノードからテキストノードが取得できていることが確認できます。

存在しない要素を指定

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

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

<script>

'use strict';

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

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

</script>

存在チェックをしておくと、エラーは回避できます。

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

if( node !== null){

    console.log(node.firstChild);

}

コードを少し簡潔に記述

また、以下のコードを、

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

console.log(node.firstChild);

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

console.log(main.firstChild);

サンプルコード

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

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

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