寫通用函式時常遇到一個問題:傳進來的參數到底是 DOM 節點,還是普通物件?用一個簡短的工具函式就能判斷。
function isDOMElement(obj) {
return !!(obj && typeof window !== 'undefined' && (obj === window || obj.nodeType));
}
這一行裡有三個判斷,各自負責一種情況:
obj:先排除 null 與 undefined,避免後續取值拋錯。typeof window !== 'undefined':確認執行環境有 DOM。在 Node.js 這類沒有 window 的環境中直接回傳 false,避免 SSR 時出錯。obj === window || obj.nodeType:window 本身沒有 nodeType,需要單獨判斷;其他元素節點則都有 nodeType 屬性。最外層的 !! 是把結果強制轉為真正的布林值,讓回傳值可直接用於條件判斷。
若需要更精細的判斷,可以進一步檢查 nodeType:
跨 iframe 時,元素的 instanceof HTMLElement 判斷會失效,因為不同 window 有各自的 HTMLElement 建構子。此時可改用:
function isDOMElement(obj) {
return obj instanceof Element;
}
// 或更保守的字串標記法
function isNode(obj) {
return typeof obj === 'object' && obj !== null && typeof obj.nodeType === 'number';
}
另外,jQuery 提供了 $.contains() 與 jQuery.isPlainObject() 等工具;若專案已載入 jQuery,直接沿用即可,不必重造輪子。