[javascript] How do you check if a JavaScript Object is a DOM Object?

I'm trying to get:

document.createElement('div')  //=> true
{tagName: 'foobar something'}  //=> false

In my own scripts, I used to just use this since I never needed tagName as a property:

if (!object.tagName) throw ...;

So for the second object, I came up with the following as a quick solution -- which mostly works. ;)

The problem is, it depends on browsers enforcing read-only properties, which not all do.

function isDOM(obj) {
  var tag = obj.tagName;
  try {
    obj.tagName = '';  // Read-only for DOM, should throw exception
    obj.tagName = tag; // Restore for normal objects
    return false;
  } catch (e) {
    return true;
  }
}

Is there a good substitute?

This question is related to javascript dom object

The answer is


I think that what you have to do is make a thorough check of some properties that will always be in a dom element, but their combination won't most likely be in another object, like so:

var isDom = function (inp) {
    return inp && inp.tagName && inp.nodeName && inp.ownerDocument && inp.removeAttribute;
};

The easiest and cross-browser way to detect if an element is part of HTML DOM is as below:

function inHTMLDom(myelement){
    if(myelement.ownerDocument.documentElement.tagName.toLowerCase()=="html"){
        return true;
    }else{
        return false;
    }
}

inHTMLDom(<your element>); // <your element>:element you are interested in checking.

tested in IE6,IE7,IE8,IE9,IE10,FF,Chrome,Safari,Opera.


I think prototyping is not a very good solution but maybe this is the fastest one: Define this code block;

Element.prototype.isDomElement = true;
HTMLElement.prototype.isDomElement = true;

than check your objects isDomElement property:

if(a.isDomElement){}

I hope this helps.


In Firefox, you can use the instanceof Node. That Node is defined in DOM1.

But that is not that easy in IE.

  1. "instanceof ActiveXObject" only can tell that it is a native object.
  2. "typeof document.body.appendChild=='object'" tell that it may be DOM object, but also can be something else have same function.

You can only ensure it is DOM element by using DOM function and catch if any exception. However, it may have side effect (e.g. change object internal state/performance/memory leak)


A absolute right method, check target is a real html element primary code:

    (function (scope) {
        if (!scope.window) {//May not run in window scope
            return;
        }
        var HTMLElement = window.HTMLElement || window.Element|| function() {};

        var tempDiv = document.createElement("div");
        var isChildOf = function(target, parent) {

            if (!target) {
                return false;
            }
            if (parent == null) {
                parent = document.body;
            }
            if (target === parent) {
                return true;
            }
            var newParent = target.parentNode || target.parentElement;
            if (!newParent) {
                return false;
            }
            return isChildOf(newParent, parent);
        }
        /**
         * The dom helper
         */
        var Dom = {
            /**
             * Detect if target element is child element of parent
             * @param {} target The target html node
             * @param {} parent The the parent to check
             * @returns {} 
             */
            IsChildOf: function (target, parent) {
                return isChildOf(target, parent);
            },
            /**
             * Detect target is html element
             * @param {} target The target to check
             * @returns {} True if target is html node
             */
            IsHtmlElement: function (target) {
                if (!X.Dom.IsHtmlNode(target)) {
                    return false;
                }
                return target.nodeType === 1;
            },
            /**
             * Detect target is html node
             * @param {} target The target to check
             * @returns {} True if target is html node
             */
            IsHtmlNode:function(target) {
                if (target instanceof HTMLElement) {
                    return true;
                }
                if (target != null) {
                    if (isChildOf(target, document.documentElement)) {
                        return true;
                    }
                    try {
                        tempDiv.appendChild(target.cloneNode(false));
                        if (tempDiv.childNodes.length > 0) {
                            tempDiv.innerHTML = "";
                            return true;
                        }
                    } catch (e) {

                    }
                }
                return false;
            }
        };
        X.Dom = Dom;
    })(this);

Test In IE 5


All solutions above and below (my solution including) suffer from possibility of being incorrect, especially on IE — it is quite possible to (re)define some objects/methods/properties to mimic a DOM node rendering the test invalid.

So usually I use the duck-typing-style testing: I test specifically for things I use. For example, if I want to clone a node I test it like this:

if(typeof node == "object" && "nodeType" in node &&
   node.nodeType === 1 && node.cloneNode){
  // most probably this is a DOM node, we can clone it safely
  clonedNode = node.cloneNode(false);
}

Basically it is a little sanity check + the direct test for a method (or a property) I am planning to use.

Incidentally the test above is a good test for DOM nodes on all browsers. But if you want to be on the safe side always check the presence of methods and properties and verify their types.

EDIT: IE uses ActiveX objects to represent nodes, so their properties do not behave as true JavaScript object, for example:

console.log(typeof node.cloneNode);              // object
console.log(node.cloneNode instanceof Function); // false

while it should return "function" and true respectively. The only way to test methods is to see if the are defined.


here's a trick using jQuery

var obj = {};
var element = document.getElementById('myId'); // or simply $("#myId")

$(obj).html() == undefined // true
$(element).html() == undefined // false

so putting it in a function:

function isElement(obj){

   return (typeOf obj === 'object' && !($(obj).html() == undefined));

}

You could try appending it to a real DOM node...

function isDom(obj)
{
    var elm = document.createElement('div');
    try
    {
        elm.appendChild(obj);
    }
    catch (e)
    {
        return false;
    }

    return true;
}

This will work for almost any browser. (No distinction between elements and nodes here)

function dom_element_check(element){
    if (typeof element.nodeType !== 'undefined'){
        return true;
    }
    return false;
}

Most answers use some kind of duck typing, checking for example that the object has a nodeType property. But that's not enough, because non-nodes can also have node-like properties.

The other common approach is instanceof, which can produce false positives e.g. with Object.create(Node), which is not a node despite inheriting node properties.

Moreover, both approaches above call internal essential methods, which can be problematic e.g. if the tested value is a proxy.

Instead, what I recommend is borrowing a node method and calling it on our object. The browser will check that the value is a node probably by looking at internal slots not customizable in proxies, so even they won't be able to interfere with our check.

function isNode(value) {
  try {
    Node.prototype.cloneNode.call(value, false);
    return true;
  } catch(err) {
    return false;
  }
}

You can also use property getters, if you prefer.

_x000D_
_x000D_
function isNode(value) {_x000D_
  try {_x000D_
    Object.getOwnPropertyDescriptor(Node.prototype,'nodeType').get.call(value);_x000D_
    return true;_x000D_
  } catch(err) {_x000D_
    return false;_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Similarly, if you want to test if a value is an element, you can use

function isElement(value) {
  try {
    Element.prototype.getAttribute.call(value, '');
    return true;
  } catch(err) {
    return false;
  }
}
function isHTMLElement(value) {
  try {
    HTMLElement.prototype.click.call(value);
    return true;
  } catch(err) {
    return false;
  }
}

This could be helpful: isDOM

//-----------------------------------
// Determines if the @obj parameter is a DOM element
function isDOM (obj) {
    // DOM, Level2
    if ("HTMLElement" in window) {
        return (obj && obj instanceof HTMLElement);
    }
    // Older browsers
    return !!(obj && typeof obj === "object" && obj.nodeType === 1 && obj.nodeName);
}

In the code above, we use the double negation operator to get the boolean value of the object passed as argument, this way we ensure that each expression evaluated in the conditional statement be boolean, taking advantage of the Short-Circuit Evaluation, thus the function returns true or false


I think that what you have to do is make a thorough check of some properties that will always be in a dom element, but their combination won't most likely be in another object, like so:

var isDom = function (inp) {
    return inp && inp.tagName && inp.nodeName && inp.ownerDocument && inp.removeAttribute;
};

This is what I figured out:

var isHTMLElement = (function () {
    if ("HTMLElement" in window) {
        // VoilĂ . Quick and easy. And reliable.
        return function (el) {return el instanceof HTMLElement;};
    } else if ((document.createElement("a")).constructor) {
        // We can access an element's constructor. So, this is not IE7
        var ElementConstructors = {}, nodeName;
        return function (el) {
            return el && typeof el.nodeName === "string" &&
                 (el instanceof ((nodeName = el.nodeName.toLowerCase()) in ElementConstructors 
                    ? ElementConstructors[nodeName] 
                    : (ElementConstructors[nodeName] = (document.createElement(nodeName)).constructor)))
        }
    } else {
        // Not that reliable, but we don't seem to have another choice. Probably IE7
        return function (el) {
            return typeof el === "object" && el.nodeType === 1 && typeof el.nodeName === "string";
        }
    }
})();

To improve performance I created a self-invoking function that tests the browser's capabilities only once and assigns the appropriate function accordingly.

The first test should work in most modern browsers and was already discussed here. It just tests if the element is an instance of HTMLElement. Very straightforward.

The second one is the most interesting one. This is its core-functionality:

return el instanceof (document.createElement(el.nodeName)).constructor

It tests whether el is an instance of the construcor it pretends to be. To do that, we need access to an element's contructor. That's why we're testing this in the if-Statement. IE7 for example fails this, because (document.createElement("a")).constructor is undefined in IE7.

The problem with this approach is that document.createElement is really not the fastest function and could easily slow down your application if you're testing a lot of elements with it. To solve this, I decided to cache the constructors. The object ElementConstructors has nodeNames as keys with its corresponding constructors as values. If a constructor is already cached, it uses it from the cache, otherwise it creates the Element, caches its constructor for future access and then tests against it.

The third test is the unpleasant fallback. It tests whether el is an object, has a nodeType property set to 1 and a string as nodeName. This is not very reliable of course, yet the vast majority of users shouldn't even fall back so far.

This is the most reliable approach I came up with while still keeping performance as high as possible.


The following IE8 compatible, super-simple code works perfectly.

The accepted answer does not detect all types of HTML elements. For example, SVG elements are not supported. In contrast, this answer works for HTML well as SVG.

See it in action here: https://jsfiddle.net/eLuhbu6r/

function isElement(element) {
    return element instanceof Element || element instanceof HTMLDocument;  
}

old thread, but here's an updated possibility for ie8 and ff3.5 users:

function isHTMLElement(o) {
    return (o.constructor.toString().search(/\object HTML.+Element/) > -1);
}

In Firefox, you can use the instanceof Node. That Node is defined in DOM1.

But that is not that easy in IE.

  1. "instanceof ActiveXObject" only can tell that it is a native object.
  2. "typeof document.body.appendChild=='object'" tell that it may be DOM object, but also can be something else have same function.

You can only ensure it is DOM element by using DOM function and catch if any exception. However, it may have side effect (e.g. change object internal state/performance/memory leak)


Most answers use some kind of duck typing, checking for example that the object has a nodeType property. But that's not enough, because non-nodes can also have node-like properties.

The other common approach is instanceof, which can produce false positives e.g. with Object.create(Node), which is not a node despite inheriting node properties.

Moreover, both approaches above call internal essential methods, which can be problematic e.g. if the tested value is a proxy.

Instead, what I recommend is borrowing a node method and calling it on our object. The browser will check that the value is a node probably by looking at internal slots not customizable in proxies, so even they won't be able to interfere with our check.

function isNode(value) {
  try {
    Node.prototype.cloneNode.call(value, false);
    return true;
  } catch(err) {
    return false;
  }
}

You can also use property getters, if you prefer.

_x000D_
_x000D_
function isNode(value) {_x000D_
  try {_x000D_
    Object.getOwnPropertyDescriptor(Node.prototype,'nodeType').get.call(value);_x000D_
    return true;_x000D_
  } catch(err) {_x000D_
    return false;_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

Similarly, if you want to test if a value is an element, you can use

function isElement(value) {
  try {
    Element.prototype.getAttribute.call(value, '');
    return true;
  } catch(err) {
    return false;
  }
}
function isHTMLElement(value) {
  try {
    HTMLElement.prototype.click.call(value);
    return true;
  } catch(err) {
    return false;
  }
}

All solutions above and below (my solution including) suffer from possibility of being incorrect, especially on IE — it is quite possible to (re)define some objects/methods/properties to mimic a DOM node rendering the test invalid.

So usually I use the duck-typing-style testing: I test specifically for things I use. For example, if I want to clone a node I test it like this:

if(typeof node == "object" && "nodeType" in node &&
   node.nodeType === 1 && node.cloneNode){
  // most probably this is a DOM node, we can clone it safely
  clonedNode = node.cloneNode(false);
}

Basically it is a little sanity check + the direct test for a method (or a property) I am planning to use.

Incidentally the test above is a good test for DOM nodes on all browsers. But if you want to be on the safe side always check the presence of methods and properties and verify their types.

EDIT: IE uses ActiveX objects to represent nodes, so their properties do not behave as true JavaScript object, for example:

console.log(typeof node.cloneNode);              // object
console.log(node.cloneNode instanceof Function); // false

while it should return "function" and true respectively. The only way to test methods is to see if the are defined.


I think that what you have to do is make a thorough check of some properties that will always be in a dom element, but their combination won't most likely be in another object, like so:

var isDom = function (inp) {
    return inp && inp.tagName && inp.nodeName && inp.ownerDocument && inp.removeAttribute;
};

You could try appending it to a real DOM node...

function isDom(obj)
{
    var elm = document.createElement('div');
    try
    {
        elm.appendChild(obj);
    }
    catch (e)
    {
        return false;
    }

    return true;
}

The only way to guarentee you're checking an actual HTMLEement, and not just an object with the same properties as an HTML Element, is to determine if it inherits from Node, since its impossible to make a new Node() in JavaScript. (unless the native Node function is overwritten, but then you're out of luck). So:

_x000D_
_x000D_
function isHTML(obj) {_x000D_
    return obj instanceof Node;_x000D_
}_x000D_
_x000D_
console.log(_x000D_
  isHTML(test),_x000D_
  isHTML(ok),_x000D_
  isHTML(p),_x000D_
  isHTML(o),_x000D_
  isHTML({_x000D_
    constructor: {_x000D_
      name: "HTML"_x000D_
    }_x000D_
  }),_x000D_
  isHTML({_x000D_
    __proto__: {_x000D_
      __proto__: {_x000D_
        __proto__: {_x000D_
          __proto__: {_x000D_
            constructor: {_x000D_
              constructor: { _x000D_
                name: "Function"_x000D_
                _x000D_
              },_x000D_
              name: "Node"_x000D_
            }_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
  }),_x000D_
)
_x000D_
<div id=test></div>_x000D_
<blockquote id="ok"></blockquote>_x000D_
<p id=p></p>_x000D_
<br id=o>_x000D_
<!--think of anything else you want--!>
_x000D_
_x000D_
_x000D_


if you are using jQuery, try this

$('<div>').is('*') // true
$({tagName: 'a'}).is('*') // false
$({}).is('*') // false
$([]).is('*') // false
$(0).is('*') // false
$(NaN).is('*') // false

I think prototyping is not a very good solution but maybe this is the fastest one: Define this code block;

Element.prototype.isDomElement = true;
HTMLElement.prototype.isDomElement = true;

than check your objects isDomElement property:

if(a.isDomElement){}

I hope this helps.


I suggest a simple way to testing if a variable is an DOM element

function isDomEntity(entity) {
  if(typeof entity  === 'object' && entity.nodeType !== undefined){
     return true;
  }
  else{
     return false;
  }
}

or as HTMLGuy suggested:

const isDomEntity = entity => {
  return typeof entity   === 'object' && entity.nodeType !== undefined
}

I have a special way to do this that has not yet been mentioned in the answers.

My solution is based on four tests. If the object passes all four, then it is an element:

  1. The object is not null.

  2. The object has a method called "appendChild".

  3. The method "appendChild" was inherited from the Node class, and isn't just an imposter method (a user-created property with an identical name).

  4. The object is of Node Type 1 (Element). Objects that inherit methods from the Node class are always Nodes, but not necessarily Elements.

Q: How do I check if a given property is inherited and isn't just an imposter?

A: A simple test to see if a method was truly inherited from Node is to first verify that the property has a type of "object" or "function". Next, convert the property to a string and check if the result contains the text "[Native Code]". If the result looks something like this:

function appendChild(){
[Native Code]
}

Then the method has been inherited from the Node object. See https://davidwalsh.name/detect-native-function

And finally, bringing all the tests together, the solution is:

function ObjectIsElement(obj) {
    var IsElem = true;
    if (obj == null) {
        IsElem = false;
    } else if (typeof(obj.appendChild) != "object" && typeof(obj.appendChild) != "function") {
        //IE8 and below returns "object" when getting the type of a function, IE9+ returns "function"
        IsElem = false;
    } else if ((obj.appendChild + '').replace(/[\r\n\t\b\f\v\xC2\xA0\x00-\x1F\x7F-\x9F ]/ig, '').search(/\{\[NativeCode]}$/i) == -1) {
        IsElem = false;
    } else if (obj.nodeType != 1) {
        IsElem = false;
    }
    return IsElem;
}

A absolute right method, check target is a real html element primary code:

    (function (scope) {
        if (!scope.window) {//May not run in window scope
            return;
        }
        var HTMLElement = window.HTMLElement || window.Element|| function() {};

        var tempDiv = document.createElement("div");
        var isChildOf = function(target, parent) {

            if (!target) {
                return false;
            }
            if (parent == null) {
                parent = document.body;
            }
            if (target === parent) {
                return true;
            }
            var newParent = target.parentNode || target.parentElement;
            if (!newParent) {
                return false;
            }
            return isChildOf(newParent, parent);
        }
        /**
         * The dom helper
         */
        var Dom = {
            /**
             * Detect if target element is child element of parent
             * @param {} target The target html node
             * @param {} parent The the parent to check
             * @returns {} 
             */
            IsChildOf: function (target, parent) {
                return isChildOf(target, parent);
            },
            /**
             * Detect target is html element
             * @param {} target The target to check
             * @returns {} True if target is html node
             */
            IsHtmlElement: function (target) {
                if (!X.Dom.IsHtmlNode(target)) {
                    return false;
                }
                return target.nodeType === 1;
            },
            /**
             * Detect target is html node
             * @param {} target The target to check
             * @returns {} True if target is html node
             */
            IsHtmlNode:function(target) {
                if (target instanceof HTMLElement) {
                    return true;
                }
                if (target != null) {
                    if (isChildOf(target, document.documentElement)) {
                        return true;
                    }
                    try {
                        tempDiv.appendChild(target.cloneNode(false));
                        if (tempDiv.childNodes.length > 0) {
                            tempDiv.innerHTML = "";
                            return true;
                        }
                    } catch (e) {

                    }
                }
                return false;
            }
        };
        X.Dom = Dom;
    })(this);

Test In IE 5


In Firefox, you can use the instanceof Node. That Node is defined in DOM1.

But that is not that easy in IE.

  1. "instanceof ActiveXObject" only can tell that it is a native object.
  2. "typeof document.body.appendChild=='object'" tell that it may be DOM object, but also can be something else have same function.

You can only ensure it is DOM element by using DOM function and catch if any exception. However, it may have side effect (e.g. change object internal state/performance/memory leak)


var IsPlainObject = function ( obj ) { return obj instanceof Object && ! ( obj instanceof Function || obj.toString( ) !== '[object Object]' || obj.constructor.name !== 'Object' ); },
    IsDOMObject = function ( obj ) { return obj instanceof EventTarget; },
    IsDOMElement = function ( obj ) { return obj instanceof Node; },
    IsListObject = function ( obj ) { return obj instanceof Array || obj instanceof NodeList; },

// In fact I am more likely t use these inline, but sometimes it is good to have these shortcuts for setup code


The only way to guarentee you're checking an actual HTMLEement, and not just an object with the same properties as an HTML Element, is to determine if it inherits from Node, since its impossible to make a new Node() in JavaScript. (unless the native Node function is overwritten, but then you're out of luck). So:

_x000D_
_x000D_
function isHTML(obj) {_x000D_
    return obj instanceof Node;_x000D_
}_x000D_
_x000D_
console.log(_x000D_
  isHTML(test),_x000D_
  isHTML(ok),_x000D_
  isHTML(p),_x000D_
  isHTML(o),_x000D_
  isHTML({_x000D_
    constructor: {_x000D_
      name: "HTML"_x000D_
    }_x000D_
  }),_x000D_
  isHTML({_x000D_
    __proto__: {_x000D_
      __proto__: {_x000D_
        __proto__: {_x000D_
          __proto__: {_x000D_
            constructor: {_x000D_
              constructor: { _x000D_
                name: "Function"_x000D_
                _x000D_
              },_x000D_
              name: "Node"_x000D_
            }_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
  }),_x000D_
)
_x000D_
<div id=test></div>_x000D_
<blockquote id="ok"></blockquote>_x000D_
<p id=p></p>_x000D_
<br id=o>_x000D_
<!--think of anything else you want--!>
_x000D_
_x000D_
_x000D_


The using the root detection found here, we can determine whether e.g. alert is a member of the object's root, which is then likely to be a window:

function isInAnyDOM(o) { 
  return (o !== null) && !!(o.ownerDocument && (o.ownerDocument.defaultView || o.ownerDocument.parentWindow).alert); // true|false
}

To determine whether the object is the current window is even simpler:

function isInCurrentDOM(o) { 
  return (o !== null) && !!o.ownerDocument && (window === (o.ownerDocument.defaultView || o.ownerDocument.parentWindow)); // true|false
}

This seems to be less expensive than the try/catch solution in the opening thread.

Don P


This is from the lovely JavaScript library MooTools:

if (obj.nodeName){
    switch (obj.nodeType){
    case 1: return 'element';
    case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
    }
}

You can see if the object or node in question returns a string type.

typeof (array).innerHTML === "string" => false
typeof (object).innerHTML === "string" => false
typeof (number).innerHTML === "string" => false
typeof (text).innerHTML === "string" => false

//any DOM element will test as true
typeof (HTML object).innerHTML === "string" => true
typeof (document.createElement('anything')).innerHTML === "string" => true

In Firefox, you can use the instanceof Node. That Node is defined in DOM1.

But that is not that easy in IE.

  1. "instanceof ActiveXObject" only can tell that it is a native object.
  2. "typeof document.body.appendChild=='object'" tell that it may be DOM object, but also can be something else have same function.

You can only ensure it is DOM element by using DOM function and catch if any exception. However, it may have side effect (e.g. change object internal state/performance/memory leak)


You could try appending it to a real DOM node...

function isDom(obj)
{
    var elm = document.createElement('div');
    try
    {
        elm.appendChild(obj);
    }
    catch (e)
    {
        return false;
    }

    return true;
}

here's a trick using jQuery

var obj = {};
var element = document.getElementById('myId'); // or simply $("#myId")

$(obj).html() == undefined // true
$(element).html() == undefined // false

so putting it in a function:

function isElement(obj){

   return (typeOf obj === 'object' && !($(obj).html() == undefined));

}

You can see if the object or node in question returns a string type.

typeof (array).innerHTML === "string" => false
typeof (object).innerHTML === "string" => false
typeof (number).innerHTML === "string" => false
typeof (text).innerHTML === "string" => false

//any DOM element will test as true
typeof (HTML object).innerHTML === "string" => true
typeof (document.createElement('anything')).innerHTML === "string" => true

Not to hammer on this or anything but for ES5-compliant browsers why not just:

function isDOM(e) {
  return (/HTML(?:.*)Element/).test(Object.prototype.toString.call(e).slice(8, -1));
}

Won't work on TextNodes and not sure about Shadow DOM or DocumentFragments etc. but will work on almost all HTML tag elements.


if you are using jQuery, try this

$('<div>').is('*') // true
$({tagName: 'a'}).is('*') // false
$({}).is('*') // false
$([]).is('*') // false
$(0).is('*') // false
$(NaN).is('*') // false

How about Lo-Dash's _.isElement?

$ npm install lodash.iselement

And in the code:

var isElement = require("lodash.iselement");
isElement(document.body);

Perhaps this is an alternative? Tested in Opera 11, FireFox 6, Internet Explorer 8, Safari 5 and Google Chrome 16.

function isDOMNode(v) {
  if ( v===null ) return false;
  if ( typeof v!=='object' ) return false;
  if ( !('nodeName' in v) ) return false; 

  var nn = v.nodeName;
  try {
    // DOM node property nodeName is readonly.
    // Most browsers throws an error...
    v.nodeName = 'is readonly?';
  } catch (e) {
    // ... indicating v is a DOM node ...
    return true;
  }
  // ...but others silently ignore the attempt to set the nodeName.
  if ( v.nodeName===nn ) return true;
  // Property nodeName set (and reset) - v is not a DOM node.
  v.nodeName = nn;

  return false;
}

Function won't be fooled by e.g. this

isDOMNode( {'nodeName':'fake'} ); // returns false

This could be helpful: isDOM

//-----------------------------------
// Determines if the @obj parameter is a DOM element
function isDOM (obj) {
    // DOM, Level2
    if ("HTMLElement" in window) {
        return (obj && obj instanceof HTMLElement);
    }
    // Older browsers
    return !!(obj && typeof obj === "object" && obj.nodeType === 1 && obj.nodeName);
}

In the code above, we use the double negation operator to get the boolean value of the object passed as argument, this way we ensure that each expression evaluated in the conditional statement be boolean, taking advantage of the Short-Circuit Evaluation, thus the function returns true or false


Each DOMElement.constructor returns function HTML...Element() or [Object HTML...Element] so...

function isDOM(getElem){
    if(getElem===null||typeof getElem==="undefined") return false;
    var c = getElem.constructor.toString();
    var html = c.search("HTML")!==-1;
    var element = c.search("Element")!==-1;
    return html&&element;
}

According to mdn

Element is the most general base class from which all objects in a Document inherit. It only has methods and properties common to all kinds of elements.

We can implement isElement by prototype. Here is my advice:

_x000D_
_x000D_
/**_x000D_
 * @description detect if obj is an element_x000D_
 * @param {*} obj_x000D_
 * @returns {Boolean}_x000D_
 * @example_x000D_
 * see below_x000D_
 */_x000D_
function isElement(obj) {_x000D_
  if (typeof obj !== 'object') {_x000D_
    return false_x000D_
  }_x000D_
  let prototypeStr, prototype_x000D_
  do {_x000D_
    prototype = Object.getPrototypeOf(obj)_x000D_
    // to work in iframe_x000D_
    prototypeStr = Object.prototype.toString.call(prototype)_x000D_
    // '[object Document]' is used to detect document_x000D_
    if (_x000D_
      prototypeStr === '[object Element]' ||_x000D_
      prototypeStr === '[object Document]'_x000D_
    ) {_x000D_
      return true_x000D_
    }_x000D_
    obj = prototype_x000D_
    // null is the terminal of object_x000D_
  } while (prototype !== null)_x000D_
  return false_x000D_
}_x000D_
console.log(isElement(document)) // true_x000D_
console.log(isElement(document.documentElement)) // true_x000D_
console.log(isElement(document.body)) // true_x000D_
console.log(isElement(document.getElementsByTagName('svg')[0])) // true or false, decided by whether there is svg element_x000D_
console.log(isElement(document.getElementsByTagName('svg'))) // false_x000D_
console.log(isElement(document.createDocumentFragment())) // false
_x000D_
_x000D_
_x000D_


You could try appending it to a real DOM node...

function isDom(obj)
{
    var elm = document.createElement('div');
    try
    {
        elm.appendChild(obj);
    }
    catch (e)
    {
        return false;
    }

    return true;
}

(element instanceof $ && element.get(0) instanceof Element) || element instanceof Element

This will check for even if it is a jQuery or JavaScript DOM element


I have a special way to do this that has not yet been mentioned in the answers.

My solution is based on four tests. If the object passes all four, then it is an element:

  1. The object is not null.

  2. The object has a method called "appendChild".

  3. The method "appendChild" was inherited from the Node class, and isn't just an imposter method (a user-created property with an identical name).

  4. The object is of Node Type 1 (Element). Objects that inherit methods from the Node class are always Nodes, but not necessarily Elements.

Q: How do I check if a given property is inherited and isn't just an imposter?

A: A simple test to see if a method was truly inherited from Node is to first verify that the property has a type of "object" or "function". Next, convert the property to a string and check if the result contains the text "[Native Code]". If the result looks something like this:

function appendChild(){
[Native Code]
}

Then the method has been inherited from the Node object. See https://davidwalsh.name/detect-native-function

And finally, bringing all the tests together, the solution is:

function ObjectIsElement(obj) {
    var IsElem = true;
    if (obj == null) {
        IsElem = false;
    } else if (typeof(obj.appendChild) != "object" && typeof(obj.appendChild) != "function") {
        //IE8 and below returns "object" when getting the type of a function, IE9+ returns "function"
        IsElem = false;
    } else if ((obj.appendChild + '').replace(/[\r\n\t\b\f\v\xC2\xA0\x00-\x1F\x7F-\x9F ]/ig, '').search(/\{\[NativeCode]}$/i) == -1) {
        IsElem = false;
    } else if (obj.nodeType != 1) {
        IsElem = false;
    }
    return IsElem;
}

This is from the lovely JavaScript library MooTools:

if (obj.nodeName){
    switch (obj.nodeType){
    case 1: return 'element';
    case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
    }
}

Each DOMElement.constructor returns function HTML...Element() or [Object HTML...Element] so...

function isDOM(getElem){
    if(getElem===null||typeof getElem==="undefined") return false;
    var c = getElem.constructor.toString();
    var html = c.search("HTML")!==-1;
    var element = c.search("Element")!==-1;
    return html&&element;
}

Perhaps this is an alternative? Tested in Opera 11, FireFox 6, Internet Explorer 8, Safari 5 and Google Chrome 16.

function isDOMNode(v) {
  if ( v===null ) return false;
  if ( typeof v!=='object' ) return false;
  if ( !('nodeName' in v) ) return false; 

  var nn = v.nodeName;
  try {
    // DOM node property nodeName is readonly.
    // Most browsers throws an error...
    v.nodeName = 'is readonly?';
  } catch (e) {
    // ... indicating v is a DOM node ...
    return true;
  }
  // ...but others silently ignore the attempt to set the nodeName.
  if ( v.nodeName===nn ) return true;
  // Property nodeName set (and reset) - v is not a DOM node.
  v.nodeName = nn;

  return false;
}

Function won't be fooled by e.g. this

isDOMNode( {'nodeName':'fake'} ); // returns false

Test if obj inherits from Node.

if (obj instanceof Node){
    // obj is a DOM Object
}

Node is a basic Interface from which HTMLElement and Text inherit.


This will work for almost any browser. (No distinction between elements and nodes here)

function dom_element_check(element){
    if (typeof element.nodeType !== 'undefined'){
        return true;
    }
    return false;
}

I suggest a simple way to testing if a variable is an DOM element

function isDomEntity(entity) {
  if(typeof entity  === 'object' && entity.nodeType !== undefined){
     return true;
  }
  else{
     return false;
  }
}

or as HTMLGuy suggested:

const isDomEntity = entity => {
  return typeof entity   === 'object' && entity.nodeType !== undefined
}

old thread, but here's an updated possibility for ie8 and ff3.5 users:

function isHTMLElement(o) {
    return (o.constructor.toString().search(/\object HTML.+Element/) > -1);
}

No need for hacks, you can just ask if an element is an instance of the DOM Element:

const isDOM = el => el instanceof Element

How about Lo-Dash's _.isElement?

$ npm install lodash.iselement

And in the code:

var isElement = require("lodash.iselement");
isElement(document.body);

The using the root detection found here, we can determine whether e.g. alert is a member of the object's root, which is then likely to be a window:

function isInAnyDOM(o) { 
  return (o !== null) && !!(o.ownerDocument && (o.ownerDocument.defaultView || o.ownerDocument.parentWindow).alert); // true|false
}

To determine whether the object is the current window is even simpler:

function isInCurrentDOM(o) { 
  return (o !== null) && !!o.ownerDocument && (window === (o.ownerDocument.defaultView || o.ownerDocument.parentWindow)); // true|false
}

This seems to be less expensive than the try/catch solution in the opening thread.

Don P


Test if obj inherits from Node.

if (obj instanceof Node){
    // obj is a DOM Object
}

Node is a basic Interface from which HTMLElement and Text inherit.


For the ones using Angular:

angular.isElement

https://docs.angularjs.org/api/ng/function/angular.isElement


All solutions above and below (my solution including) suffer from possibility of being incorrect, especially on IE — it is quite possible to (re)define some objects/methods/properties to mimic a DOM node rendering the test invalid.

So usually I use the duck-typing-style testing: I test specifically for things I use. For example, if I want to clone a node I test it like this:

if(typeof node == "object" && "nodeType" in node &&
   node.nodeType === 1 && node.cloneNode){
  // most probably this is a DOM node, we can clone it safely
  clonedNode = node.cloneNode(false);
}

Basically it is a little sanity check + the direct test for a method (or a property) I am planning to use.

Incidentally the test above is a good test for DOM nodes on all browsers. But if you want to be on the safe side always check the presence of methods and properties and verify their types.

EDIT: IE uses ActiveX objects to represent nodes, so their properties do not behave as true JavaScript object, for example:

console.log(typeof node.cloneNode);              // object
console.log(node.cloneNode instanceof Function); // false

while it should return "function" and true respectively. The only way to test methods is to see if the are defined.


No need for hacks, you can just ask if an element is an instance of the DOM Element:

const isDOM = el => el instanceof Element

All solutions above and below (my solution including) suffer from possibility of being incorrect, especially on IE — it is quite possible to (re)define some objects/methods/properties to mimic a DOM node rendering the test invalid.

So usually I use the duck-typing-style testing: I test specifically for things I use. For example, if I want to clone a node I test it like this:

if(typeof node == "object" && "nodeType" in node &&
   node.nodeType === 1 && node.cloneNode){
  // most probably this is a DOM node, we can clone it safely
  clonedNode = node.cloneNode(false);
}

Basically it is a little sanity check + the direct test for a method (or a property) I am planning to use.

Incidentally the test above is a good test for DOM nodes on all browsers. But if you want to be on the safe side always check the presence of methods and properties and verify their types.

EDIT: IE uses ActiveX objects to represent nodes, so their properties do not behave as true JavaScript object, for example:

console.log(typeof node.cloneNode);              // object
console.log(node.cloneNode instanceof Function); // false

while it should return "function" and true respectively. The only way to test methods is to see if the are defined.


According to mdn

Element is the most general base class from which all objects in a Document inherit. It only has methods and properties common to all kinds of elements.

We can implement isElement by prototype. Here is my advice:

_x000D_
_x000D_
/**_x000D_
 * @description detect if obj is an element_x000D_
 * @param {*} obj_x000D_
 * @returns {Boolean}_x000D_
 * @example_x000D_
 * see below_x000D_
 */_x000D_
function isElement(obj) {_x000D_
  if (typeof obj !== 'object') {_x000D_
    return false_x000D_
  }_x000D_
  let prototypeStr, prototype_x000D_
  do {_x000D_
    prototype = Object.getPrototypeOf(obj)_x000D_
    // to work in iframe_x000D_
    prototypeStr = Object.prototype.toString.call(prototype)_x000D_
    // '[object Document]' is used to detect document_x000D_
    if (_x000D_
      prototypeStr === '[object Element]' ||_x000D_
      prototypeStr === '[object Document]'_x000D_
    ) {_x000D_
      return true_x000D_
    }_x000D_
    obj = prototype_x000D_
    // null is the terminal of object_x000D_
  } while (prototype !== null)_x000D_
  return false_x000D_
}_x000D_
console.log(isElement(document)) // true_x000D_
console.log(isElement(document.documentElement)) // true_x000D_
console.log(isElement(document.body)) // true_x000D_
console.log(isElement(document.getElementsByTagName('svg')[0])) // true or false, decided by whether there is svg element_x000D_
console.log(isElement(document.getElementsByTagName('svg'))) // false_x000D_
console.log(isElement(document.createDocumentFragment())) // false
_x000D_
_x000D_
_x000D_


var IsPlainObject = function ( obj ) { return obj instanceof Object && ! ( obj instanceof Function || obj.toString( ) !== '[object Object]' || obj.constructor.name !== 'Object' ); },
    IsDOMObject = function ( obj ) { return obj instanceof EventTarget; },
    IsDOMElement = function ( obj ) { return obj instanceof Node; },
    IsListObject = function ( obj ) { return obj instanceof Array || obj instanceof NodeList; },

// In fact I am more likely t use these inline, but sometimes it is good to have these shortcuts for setup code


This is from the lovely JavaScript library MooTools:

if (obj.nodeName){
    switch (obj.nodeType){
    case 1: return 'element';
    case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
    }
}

differentiate a raw js object from a HTMLElement

function isDOM (x){
     return /HTML/.test( {}.toString.call(x) );
 }

use:

isDOM( {a:1} ) // false
isDOM( document.body ) // true

// OR

Object.defineProperty(Object.prototype, "is",
    {
        value: function (x) {
            return {}.toString.call(this).indexOf(x) >= 0;
        }
    });

use:

o={}; o.is("HTML") // false o=document.body; o.is("HTML") // true


This is what I figured out:

var isHTMLElement = (function () {
    if ("HTMLElement" in window) {
        // VoilĂ . Quick and easy. And reliable.
        return function (el) {return el instanceof HTMLElement;};
    } else if ((document.createElement("a")).constructor) {
        // We can access an element's constructor. So, this is not IE7
        var ElementConstructors = {}, nodeName;
        return function (el) {
            return el && typeof el.nodeName === "string" &&
                 (el instanceof ((nodeName = el.nodeName.toLowerCase()) in ElementConstructors 
                    ? ElementConstructors[nodeName] 
                    : (ElementConstructors[nodeName] = (document.createElement(nodeName)).constructor)))
        }
    } else {
        // Not that reliable, but we don't seem to have another choice. Probably IE7
        return function (el) {
            return typeof el === "object" && el.nodeType === 1 && typeof el.nodeName === "string";
        }
    }
})();

To improve performance I created a self-invoking function that tests the browser's capabilities only once and assigns the appropriate function accordingly.

The first test should work in most modern browsers and was already discussed here. It just tests if the element is an instance of HTMLElement. Very straightforward.

The second one is the most interesting one. This is its core-functionality:

return el instanceof (document.createElement(el.nodeName)).constructor

It tests whether el is an instance of the construcor it pretends to be. To do that, we need access to an element's contructor. That's why we're testing this in the if-Statement. IE7 for example fails this, because (document.createElement("a")).constructor is undefined in IE7.

The problem with this approach is that document.createElement is really not the fastest function and could easily slow down your application if you're testing a lot of elements with it. To solve this, I decided to cache the constructors. The object ElementConstructors has nodeNames as keys with its corresponding constructors as values. If a constructor is already cached, it uses it from the cache, otherwise it creates the Element, caches its constructor for future access and then tests against it.

The third test is the unpleasant fallback. It tests whether el is an object, has a nodeType property set to 1 and a string as nodeName. This is not very reliable of course, yet the vast majority of users shouldn't even fall back so far.

This is the most reliable approach I came up with while still keeping performance as high as possible.


differentiate a raw js object from a HTMLElement

function isDOM (x){
     return /HTML/.test( {}.toString.call(x) );
 }

use:

isDOM( {a:1} ) // false
isDOM( document.body ) // true

// OR

Object.defineProperty(Object.prototype, "is",
    {
        value: function (x) {
            return {}.toString.call(this).indexOf(x) >= 0;
        }
    });

use:

o={}; o.is("HTML") // false o=document.body; o.is("HTML") // true


The following IE8 compatible, super-simple code works perfectly.

The accepted answer does not detect all types of HTML elements. For example, SVG elements are not supported. In contrast, this answer works for HTML well as SVG.

See it in action here: https://jsfiddle.net/eLuhbu6r/

function isElement(element) {
    return element instanceof Element || element instanceof HTMLDocument;  
}

var isElement = function(e){
    try{
        // if e is an element attached to the DOM, we trace its lineage and use native functions to confirm its pedigree
        var a = [e], t, s, l = 0, h = document.getElementsByTagName('HEAD')[0], ht = document.getElementsByTagName('HTML')[0];
        while(l!=document.body&&l!=h&&l.parentNode) l = a[a.push(l.parentNode)-1];
        t = a[a.length-1];
        s = document.createElement('SCRIPT');   // safe to place anywhere and it won't show up
        while(a.length>1){  // assume the top node is an element for now...
            var p = a.pop(),n = a[a.length-1];
            p.insertBefore(s,n);
        }
        if(s.parentNode)s.parentNode.removeChild(s);
        if(t!=document.body&&t!=h&&t!=ht)
            // the top node is not attached to the document, so we don't have to worry about it resetting any dynamic media
            // test the top node
            document.createElement('DIV').appendChild(t).parentNode.removeChild(t);
        return e;
    }
    catch(e){}
    return null;
}

I tested this on Firefox, Safari, Chrome, Opera and IE9. I couldn't find a way to hack it.
In theory, it tests every ancestor of the proposed element, as well as the element itself, by inserting a script tag before it.
If its first ancestor traces back to a known element, such as <html>, <head> or <body>, and it hasn't thrown an error along the way, we have an element.
If the first ancestor is not attached to the document, we create an element and attempt to place the proposed element inside of it, (and then remove it from the new element).
So it either traces back to a known element, successfully attaches to a known element or fails.
It returns the element or null if it is not an element.


I think that what you have to do is make a thorough check of some properties that will always be in a dom element, but their combination won't most likely be in another object, like so:

var isDom = function (inp) {
    return inp && inp.tagName && inp.nodeName && inp.ownerDocument && inp.removeAttribute;
};

Not to hammer on this or anything but for ES5-compliant browsers why not just:

function isDOM(e) {
  return (/HTML(?:.*)Element/).test(Object.prototype.toString.call(e).slice(8, -1));
}

Won't work on TextNodes and not sure about Shadow DOM or DocumentFragments etc. but will work on almost all HTML tag elements.


var isElement = function(e){
    try{
        // if e is an element attached to the DOM, we trace its lineage and use native functions to confirm its pedigree
        var a = [e], t, s, l = 0, h = document.getElementsByTagName('HEAD')[0], ht = document.getElementsByTagName('HTML')[0];
        while(l!=document.body&&l!=h&&l.parentNode) l = a[a.push(l.parentNode)-1];
        t = a[a.length-1];
        s = document.createElement('SCRIPT');   // safe to place anywhere and it won't show up
        while(a.length>1){  // assume the top node is an element for now...
            var p = a.pop(),n = a[a.length-1];
            p.insertBefore(s,n);
        }
        if(s.parentNode)s.parentNode.removeChild(s);
        if(t!=document.body&&t!=h&&t!=ht)
            // the top node is not attached to the document, so we don't have to worry about it resetting any dynamic media
            // test the top node
            document.createElement('DIV').appendChild(t).parentNode.removeChild(t);
        return e;
    }
    catch(e){}
    return null;
}

I tested this on Firefox, Safari, Chrome, Opera and IE9. I couldn't find a way to hack it.
In theory, it tests every ancestor of the proposed element, as well as the element itself, by inserting a script tag before it.
If its first ancestor traces back to a known element, such as <html>, <head> or <body>, and it hasn't thrown an error along the way, we have an element.
If the first ancestor is not attached to the document, we create an element and attempt to place the proposed element inside of it, (and then remove it from the new element).
So it either traces back to a known element, successfully attaches to a known element or fails.
It returns the element or null if it is not an element.


For the ones using Angular:

angular.isElement

https://docs.angularjs.org/api/ng/function/angular.isElement


The easiest and cross-browser way to detect if an element is part of HTML DOM is as below:

function inHTMLDom(myelement){
    if(myelement.ownerDocument.documentElement.tagName.toLowerCase()=="html"){
        return true;
    }else{
        return false;
    }
}

inHTMLDom(<your element>); // <your element>:element you are interested in checking.

tested in IE6,IE7,IE8,IE9,IE10,FF,Chrome,Safari,Opera.


(element instanceof $ && element.get(0) instanceof Element) || element instanceof Element

This will check for even if it is a jQuery or JavaScript DOM element


This is from the lovely JavaScript library MooTools:

if (obj.nodeName){
    switch (obj.nodeType){
    case 1: return 'element';
    case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
    }
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor