开发者

Checking if object is a DOM-element [duplicate]

This question already 开发者_StackOverflow中文版has answers here: How do you check if a JavaScript Object is a DOM Object? (36 answers) Closed 6 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜