JavaScript firstElementChildメソッドを使って1階層下の最初のhtmlタグを取得する

環境
Google Chrome  115.0.5790.171(Official Build) (64 ビット)
Windows 11 Pro 64bit

構文
document.getElementById( “セレクターid名" ).firstElementChild ;
firstElementChild」メソッドを使って、最初の1つだけの子要素を取得します。

使用例

<!DOCTYPE html>
<html>
<body>

<ul id="txt" >
  <li>東京</li>
  <li>大阪</li>
  <li>福岡</li>
</ul>


<button onclick="funA()">表示</button>

<script>
function funA() {
let ele = document.getElementById( "txt" ).firstElementChild ;

console.log(ele) 

console.log(ele.innerHTML) 
}
</script>

</body>
</html>

実行結果
li
東京

JavaScript

Posted by arkgame