JavaScript の childElementCount で直接の子要素を数える

JavaScript で直接の子要素の数を読み取るには element.childElementCount を使います。テキストとコメントは数えません。子の中に入っている要素は子孫ですが、直接の子要素には含まれません。

直接の子要素だけを数える

例では二つの li を作り、一方に strong を入れます。childElementCount と children.length はどちらも2です。querySelectorAll('*').length は入れ子の要素も含めて3になります。DOM Standard · childElementCount

const list = document.createElement('ul');
const first = document.createElement('li');
first.append(document.createElement('strong'));
list.append(first, document.createComment('note'), document.createElement('li'));

console.log(list.childElementCount);            // 2
console.log(list.children.length);              // 2
console.log(list.querySelectorAll('*').length);  // 3
console.log(list.childNodes.length);            // 3

テキストノードやコメントも含める場合は childNodes.length を使います。この例には直接の子として二つの li と一つのコメントがあるので3です。HTML のインデントで空白のテキストノードが増える場合もあります。DOM Standard · childNodes

変更後に数を読み直す

childElementCount は読み取り専用です。append() や remove() でリストを変更した後、値を読み直します。変数に保存した数は以前の値のままなので、画面に表示する場合は変更後に更新します。

const list = document.createElement('ul');
list.append(document.createElement('li'));

const before = list.childElementCount;
const item = document.createElement('li');
list.append(item);
console.log(before, list.childElementCount); // 1, 2

item.remove();
console.log(list.childElementCount); // 1

サンプルでリスト項目を追加・削除する

コードを UTF-8 の child-element-count.html として保存し、ブラウザーで開きます。初期状態では直接の子要素が2個、子孫要素が3個です。追加すると3と4になり、最後の項目を削除すると2と3に戻ります。

<!doctype html>
<html lang="ja">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>子要素を数える</title>
</head>
<body>
<ul id="items">
  <li>項目 1 <strong>入れ子の強調</strong></li>
  <li>項目 2</li>
</ul>
<button id="add" type="button">項目を追加</button>
<button id="remove" type="button">最後の項目を削除</button>
<p id="count" aria-live="polite"></p>
<script>
const list = document.querySelector('#items');
const count = document.querySelector('#count');
let nextNumber = 3;

function update() {
  const descendants = list.querySelectorAll('*').length;
  count.textContent = `直接の子要素: ${list.childElementCount} · すべての子孫要素: ${descendants}`;
}

document.querySelector('#add').addEventListener('click', () => {
  const item = document.createElement('li');
  item.textContent = `項目 ${nextNumber++}`;
  list.append(item);
  update();
});
document.querySelector('#remove').addEventListener('click', () => {
  list.lastElementChild?.remove();
  update();
});
update();
</script>
</body>
</html>

すべての項目を消すと両方とも0になります。空のリストの lastElementChild は null です。?.remove() は削除対象があるときだけ実行されます。