0

Possible Duplicate:
Javascript isDOM — How do you check if a Javascript Object is a DOM Object?

In my code, I have an object which takes a DOM element.

Code below has been changed to their minimum in order to keep example clear.

var Test = function(element){
  //if element does not come from the DOM -> throw
};

How can I be sure this element comes from the DOM tree?

if(element.parentNode === null) {
  throw "not coming from the DOM";
}

Is this code enough to state element comes from DOM ?

Community
  • 1
  • 1
dervlap
  • 406
  • 4
  • 14
  • That will crash if element is null (or undefined). Are you trying to distinguish between elements in the document and detached elements, or between DOM elements and other types of objects entirely? – nnnnnn Oct 19 '12 at 08:57
  • Check if 'the element is not null' and 'element is equal to the html element or the parentNode is not null' – Asciiom Oct 19 '12 at 08:59

1 Answers1

0

You can do this with jQuery, The jQuery object $("#myid") always returns something - a jQuery object. To check if it actually represents an existing DOM element on the page you can use the following:

if ( $("#myid").length > 0 ) {
//do something
}

or alternatively based on this answer you can check it like this:

var elementInDocument = function(element) {
    while (element = element.parentNode) {
        if (element == document) {
            return true;
        }
    }
    return false;
}

or like this:

var element =  document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
  // exists.
}
Community
  • 1
  • 1
03Usr
  • 3,335
  • 6
  • 37
  • 63