jQuery 選擇器永遠返回 jQuery 對象 (類數組),即使元素不存在也返回空對象 (`length === 0`),而非 `null`。這導致傳統 `if ($('#id'))` 判斷失效。本文講解正確判斷方法及最佳實踐。
// 錯誤!永遠為 true,因為 $() 返回對象 (truthy)
if ($('#myId')) {
console.log('存在'); // 即使元素不存在也會執行
}
if ($('#myId').length > 0) {
console.log('元素存在');
} else {
console.log('元素不存在');
}
// 簡寫 (0 為 falsy)
if ($('#myId').length) { ... }
$.fn.exists = function() {
return this.length > 0;
};
// 使用
if ($('#myId').exists()) { ... }
// 方法一:getElementById (最快,僅限 ID)
if (document.getElementById('myId')) { ... }
// 方法二:querySelector (支持任意選擇器)
if (document.querySelector('#myId')) { ... }
if (document.querySelector('.my-class')) { ... }
// 方法三:getElementsByClassName / getElementsByTagName
if (document.getElementsByClassName('my-class').length) { ... }
| 方法 | 性能 | 適用場景 |
|---|---|---|
| document.getElementById | ⚡️ 最快 (原生、哈希查找) | 已知 ID、高頻調用 |
| document.querySelector | 快 (原生、選擇器引擎) | 複雜選擇器、單個元素 |
| $().length | 中等 (jQuery 封裝開銷) | 已在 jQuery 鏈式調用中、複雜選擇器 |
// display:none / visibility:hidden / opacity:0 仍然「存在」
$('#hidden').length === 1; // true
// 判斷可見性需額外檢查
$('#hidden').is(':visible'); // false
// AJAX 載入後才存在的元素
$.get('/data', function(html) {
$('#container').html(html);
// 此時才能判斷
if ($('#dynamic-element').length) { ... }
});
// 無法直接訪問跨域 iframe 內元素
// 需 postMessage 通信或同域下:
var iframeDoc = $('#myIframe')[0].contentDocument;
if (iframeDoc.getElementById('innerId')) { ... }
<html>
<head>
<script src="jquery-3.6.0.min.js"></script>
<script>
$(function() {
// 正確判斷
if ($('#exist').length) console.log('存在');
else console.log('不存在');
if ($('#not-exist').length) console.log('存在');
else console.log('不存在'); // 輸出此行
// 原生對比
if (document.getElementById('exist')) console.log('原生: 存在');
});
</script>
</head>
<body>
<div id="exist">我存在</div>
</body>
</html>