Frankly
Frankly

Reputation: 31

Test if object is a DOM element

A JavaScript function receives one argument that may be a DOM element or not. How ensure that argument is a DOM element and not another object?

Upvotes: 3

Views: 426

Answers (4)

c-smile
c-smile

Reputation: 27460

el instanceof Node will give you true if el is a part of DOM. el instanceof Element - true if it is also an Element.

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69905

Try this.

To check if it is a DOM object.

if(arg.tagName){ 
   //Its a dom element
}

To check if it is a jQuery object

if(arg.jquery){
   //Its a jQuery object
}

Working demo

Alternatively you can try this function which will return true if the element passed as an argument is a DOM element.

function isElement(o){
  return (
    typeof HTMLElement === "object" ? o instanceof HTMLElement :
    typeof o === "object" && o.nodeType === 1 && typeof o.nodeName==="string"
);

Upvotes: 1

user555742
user555742

Reputation: 68

just check the object that is it have a innerHTML function or not.

For example :

function (obj ) {
    if(!!obj.innerHTML) // force the function to be boolean 
    {
         // do something here if it was a html element 
    }
    else {
         // do stuff here if it wasn't
    }



}

Upvotes: 0

Leonid
Leonid

Reputation: 3171

With modern browsers I think it is something like

e instanceof Element
e instanceof Text // text node

Upvotes: 2

Related Questions