I have a function:
function Check(o)
{
alert(/* o is a DOM element ? "true" : "false" */);
}
How can I check if the parameter o is a DOM object or not?
I have a function:
function Check(o)
{
alert(/* o is a DOM element ? "true" : "false" */);
}
How can I check if the parameter o is a DOM object or not?
A DOM element implements the Element interface. So you can use:
function Check(o) {
alert(o instanceof Element);
}
Check if the nodeName property exists.
Basically check if it is a Node: look at the DOM lvl 1 specs, check the Node definition.
If you meant it literally when you said Element check for tagName property, look at the Element definition in the same spec
So to recap, do either
function Check(o)
{
alert(o.tagName ? "true" : "false");
}
to check if it is a DOM Element or
function Check(o)
{
alert(o.nodeName ? "true" : "false" );
}
to check if it is a DOM Node
Instead of just checking for the existence of a property, I'd check its specific value.
This assumes you're looking for a "type 1" element.
function Check(o) {
alert( o && o.nodeType && o.nodeType === 1 );
}
You could still get an object that has the nodeType property that isn't actually a DOM node, but it would also have to have a matching value of 1 to give a false positive.
Late answer, but a document fragment could be a node as well:
function isNode(node) {
return node && (node.nodeType === 1 || node.nodeType == 11);
}
Credits: https://github.com/k-gun/so/blob/4.8.1/so.dom.js#L50
You can use the following function
function isNode(o)
{
return o && 'nodeType' in o;
}