Search code examples
javascriptdomweb-worker

Checking if object is a DOM-element


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

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