Question

This question already has an answer here:

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
Was it helpful?

Solution

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;
}​

OTHER TIPS

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

Check s instanceof Node. Every DOM object is a Node.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top