Say for instance I was writing a function that was designed to accept multiple argument types:
var overloaded = function (arg) {
if (is_dom_element(arg)) {
// Code for DOM Element argument...
}
};
What's the best way to implement is_dom_element
so that it works in a cross-browser, fairly accurate way?
The HTML DOM is a standard object model and programming interface for HTML. It defines: The HTML elements as objects.
Definition and Usage. The nodeType property returns the node type, as a number, of the specified node. If the node is an element node, the nodeType property will return 1. If the node is an attribute node, the nodeType property will return 2. If the node is a text node, the nodeType property will return 3.
jQuery checks the nodeType property. So you would have:
var overloaded = function (arg) {
if (arg.nodeType) {
// Code for DOM Element argument...
}
};
Although this would detect all DOM objects, not just elements. If you want elements alone, that would be:
var overloaded = function (arg) {
if (arg.nodeType && arg.nodeType == 1) {
// Code for DOM Element argument...
}
};
Probably this one here:
node instanceof HTMLElement
That should work in most browsers. Otherwise you have to duck-type it (eg. typeof x.nodeType != 'undefined'
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With