Checking if object is a DOM-element [duplicate]
Passing DOM elements to WebWorkers gets tricky since all references to the DOM are 'lost'. I need to check objects that are passed before the WebWorker's message is sent.
What is the fastest way to check if an instance of an object is a DOM-element OR/AND part of the DOM tree, OR has 'children' that contain any references to the DOM tree?
piece of the usage:
var a = new SharedWorker("bigdatahandler.js");
a.postMessage(s);
s //<--should not be a DOM object
To check whether an object is an Element instance, use instanceof
:
s instanceof Element
And to check its owner document, use ownerDocument
:
s.ownerDocument == document
To check if it's an element I think obj.nodeName
is your best bet.
var a = new SharedWorker("bigdatahandler.js");
if (!s.nodeName) {
a.postMessage(s);
}
You can also check s instanceof Element
, because you don't need to support IE I guess :)
To check if it's part of the DOM:
function inDOM(elem) {
do {
if (elem == document.documentElement) {
return true;
}
} while (elem = elem.parentNode)
return false;
}
Check s instanceof Node
. Every DOM object is a Node
.
精彩评论