This question has sort of been asked before, but (a) a long time ago and (b) some of the past answers include jQuery.
For current browsers (including IE >= 8) what is the simplest reliable way to test whether a variable is a DOM element?
I don’t care whether the element is currently in the DOM. I’m more interested in whether the variable contains a valid element object.
I am writing a function which needs to choose between a document element and a string. Here is my take on it:
function doit(element) {
if (element instanceof Element) {
// document element
} else if (typeof element == 'string') {
// string
}
// else out of luck
}
Here have used instanceof
for the Element and typeof
for the string, piecing together what I have read elsewhere.
In today’s browsers (and yesterday's if you include IE), is this the most efficient/correct method?
Thanks