javascript nodeNameでノードの名前を取得する

javascript nodeNameでノードの名前を取得する

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

環境

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

nodeName使い方

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

ノード.nodeName

nodeName使い方

<div id="main"></div>test-node<!-- コメント -->

<script>

'use strict';

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

// 要素ノード
console.log(node.nodeName) // DIV
// 次のノード(テキストノード)
console.log(node.nextSibling.nodeName) // #text
// 次のノード(コメントノード)
console.log(node.nextSibling.nextSibling.nodeName) // #comment

</script>

実行結果を見ると、各種類のノードの名前が表示されているが確認できます。

また、以下のコードを、

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

// 要素ノード
console.log(node.nodeName) // DIV

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

console.log(main.nodeName) // DIV

サンプルコード

以下は、
「取得」ボタンをクリックして、自身の要素ノードの名前を表示するだけの
サンプルコードとなります。

※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 = () => {

    btn.onclick = () => {      
      btn.innerHTML = btn.nodeName;
    };

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">
      <button id="btn"
        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>

要素ノードが表示されていることが確認できます。