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?
With modern browsers I think it is something like
e instanceof Element
e instanceof Text // text node
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"
);
el instanceof Node
will give you true
if el is a part of DOM.
el instanceof Element
- true
if it is also an Element.
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
}
}
精彩评论