萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 獲取子元素個數完整指南:children()、find() 與原生替代方案

jQuery 子元素計數完整解析:children() vs find()、選取器差異與效能優化

獲取子元素數量是 DOM 操作基礎操作。本文詳細比較 jQuery .children()、.find()、原生 childElementCount 等方法的差異、適用場景與效能特徵。

核心方法對照表

方法範圍選取器支援返回類型修改原集合
.children([selector])直接子元素 (第 1 層)可選過濾jQuery 物件否
.find(selector)所有後代 (無限層級)必填jQuery 物件否
.contents()子節點 (含文字/註解節點)無jQuery 物件否
DOM.childElementCount直接子元素無NumberN/A
DOM.children.length直接子元素 (HTMLCollection)無NumberN/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 (含文字節點 "文字節點")

關鍵差異深度解析

children() vs find()


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() - 所有直接子元素

jQuery 物件 vs 原生集合


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 (即時更新)

效能比較 (1000 次操作)


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 的子元素」
  • iframe 內容不可跨域存取:受同源策略限制
  • SVG 元素: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 內
}

TypeScript 型別定義


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;
}
copyright © 萬盛學電腦網 all rights reserved