JavaScript nodeNameを使ってノードの名前を取得する

環境
Google Chrome 109.0.5414.120
Windows 10 Home 64bit

書式
const 変数名 = document.getElementById(“セレクターID名");
要素ノードの取得
変数名.nodeName
次のノードの取得
変数名.nextSibling.nodeName

使用例

<!DOCTYPE html>
<html>
<body>

<div id="city">東京サンプルのデータ</div><br>

<button onclick="funA()">テスト</button>

<script>
function funA() {
const cft = document.getElementById("city");

// 要素ノード
console.log(cft.nodeName)
// 次のノード(テキストノード)
console.log(cft.nextSibling.nodeName) // #text
// 次のノード(コメントノード)
console.log(cft.nextSibling.nextSibling.nodeName) 
}
</script>

</body>
</html>

実行結果
DIV
BR
#text

JavaScript

Posted by arkgame