Reputation: 31
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
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
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
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
Reputation: 3171
With modern browsers I think it is something like
e instanceof Element
e instanceof Text // text node
Upvotes: 2