獲取子元素數量是 DOM 操作基礎操作。本文詳細比較 jQuery .children()、.find()、原生 childElementCount 等方法的差異、適用場景與效能特徵。
| 方法 | 範圍 | 選取器支援 | 返回類型 | 修改原集合 |
|---|---|---|---|---|
| .children([selector]) | 直接子元素 (第 1 層) | 可選過濾 | jQuery 物件 | 否 |
| .find(selector) | 所有後代 (無限層級) | 必填 | jQuery 物件 | 否 |
| .contents() | 子節點 (含文字/註解節點) | 無 | jQuery 物件 | 否 |
| DOM.childElementCount | 直接子元素 | 無 | Number | N/A |
| DOM.children.length | 直接子元素 (HTMLCollection) | 無 | Number | N/A |
<div id="div1">
<span class="item">A</span>
<span class="item">B</span>
<div class="nested">
<span class="item">C</span> <!-- 孫元素 -->
</div>
<p>文字節點</p>
</div>
<script>
// 1. 直接子元素總數 (含 p、div、span)
$('#div1').children().length; // 4
// 2. 直接子元素中符合選取器的數量
$('#div1').children('span').length; // 2 (只算直接子層的 span)
$('#div1').children('.item').length; // 2
// 3. 所有後代元素 (含巢狀)
$('#div1').find('span').length; // 3 (含孫元素 C)
$('#div1').find('.item').length; // 3
// 4. 原生 DOM (最高效能)
document.getElementById('div1').childElementCount; // 4
document.getElementById('div1').children.length; // 4 (HTMLCollection, 即時更新)
// 5. 含文字節點計數
$('#div1').contents().length; // 5 (含文字節點 "文字節點")
const $container = $('#container');
// children(): 僅第一層
$container.children(); // 所有直接子元素
$container.children('.active'); // 直接子元素中 class=active
// find(): 所有後代 (遞歸)
$container.find('.active'); // 所有後代中 class=active
$container.find('> .active'); // 等同 children('.active') - 直接子元素
$container.find('> *'); // 等同 children() - 所有直接子元素
const $children = $('#div1').children(); // jQuery 物件,靜態快照
const nativeChildren = document.getElementById('div1').children; // HTMLCollection,即時動態
// 動態新增元素測試
$('#div1').append('New');
console.log($children.length); // 4 (不變,快照)
console.log(nativeChildren.length); // 5 (即時更新)
const $el = $('#div1');
const el = $el[0];
console.time('jQuery children().length');
for (let i=0; i<1000; i++) $el.children().length;
console.timeEnd('jQuery children().length'); // ~8ms
console.time('jQuery find().length');
for (let i=0; i<1000; i++) $el.find('> *').length;
console.timeEnd('jQuery find().length'); // ~12ms
console.time('Native childElementCount');
for (let i=0; i<1000; i++) el.childElementCount;
console.timeEnd('Native childElementCount'); // ~0.3ms (最快)
console.time('Native children.length');
for (let i=0; i<1000; i++) el.children.length;
console.timeEnd('Native children.length'); // ~0.4ms
display:none 不影響計數childElementCount / .children() 只算 Element 節點$('#div1').children('span') 先找所有子元素再過濾,非「找 span 的子元素」children 包含 SVG 子元素,childElementCount 同樣計算
function updateCount() {
const count = $('#itemList').children().length;
$('#itemCount').text(count);
$('#emptyState').toggle(count === 0);
}
// 事件委託監聽動態變化
$('#itemList').on('DOMNodeInserted DOMNodeRemoved', '> *', updateCount);
// 或現代 MutationObserver
new MutationObserver(updateCount).observe(document.getElementById('itemList'), { childList: true });
function validateRequiredFields(formId) {
const $form = $(formId);
const requiredInputs = $form.find('[required]').get();
const emptyCount = requiredInputs.filter(el => !el.value.trim()).length;
if (emptyCount > 0) {
alert(`尚有 ${emptyCount} 個必填欄位未填寫`);
return false;
}
return true;
}
function shouldLoadMore() {
const $container = $('#feed');
const items = $container.children().length;
const lastItem = $container.children().last()[0];
if (!lastItem) return true; // 空容器
const rect = lastItem.getBoundingClientRect();
return rect.top < window.innerHeight + 200; // 距離視口底部 200px 內
}
interface JQuery {
children(selector?: string): JQuery;
find(selector: string): JQuery;
contents(): JQuery;
}
interface Element {
readonly childElementCount: number;
readonly children: HTMLCollection;
// querySelectorAll 返回靜態 NodeList
querySelectorAll(selectors: string): NodeListOf;
}
// 型別安全輔助
function getChildCount(element: Element, selector?: string): number {
if (selector) {
return element.querySelectorAll(':scope > ' + selector).length;
}
return element.childElementCount;
}