JavaScript childrenプロパティを使って子要素の数を取得する
環境
Google Chrome 111.0.5563.147
Windows 10 Home 64bit
書式
document.querySelector('.クラス名).children.length;
childrenプロパティを使ってlengthプロパティで子要素の数を取得します。
使用例
<!DOCTYPE html>
<html>
<body>
<ul class="city">
<li>tokyo</li>
<li>oosaka</li>
<li>fukuoka</li>
</ul>
<button>確認</button>
<script>
function chk() {
let res = document.querySelector('.city').children.length;
console.log("子要素の数: "+res);
}
</script>
</body>
</html>
実行結果
子要素の数: 3