0

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

Manngo
  • 14,066
  • 10
  • 88
  • 110
  • You mean, you want to test that your element is actually in the DOM ? If yes your code doesn't work – Steeve Pitis Oct 10 '16 at 08:51
  • Good point. No, I mean whether the variable contains a valid HTML element. I’ll edit the question. – Manngo Oct 10 '16 at 08:52
  • "Document element" has a specific meaning, which is `Node.nodeType === Node.DOCUMENT_NODE`--the node often displayed as `#document` in devtools, for example. If that's not what you mean, then please choose different terminology. If you mean "DOM element", then say that. –  Oct 10 '16 at 09:28

1 Answers1

-1

You could check it the other way around like:

function doit(element) {
    if(typeof element === 'string') { // to be save -> always use type check in js (===)
        //  string
    }
    else {
        //  assuming it is a document element
    }
}

If you really want to check it on HTML element, you can also rely on this post.

Spoiler: ... instanceof HTMLElement

Community
  • 1
  • 1
bash0ne
  • 394
  • 3
  • 14
  • I saw that one before. The problem is (a) it’s jQuery related, and (b) I don’t think it’s safe to assume it’s not something else like a number or another object. – Manngo Oct 10 '16 at 08:56
  • Why is it jQuery related? It comes from the [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement). True story It is not the best way to differentiate but it is one of the fastest ways. – bash0ne Oct 10 '16 at 09:00
  • @bashOne: The question reads: “jquery: test whether input variable is dom element”, though it’s true that the question itself doesn’t seem to press the point. The MDN documentation is unclear whether this is supported in IE8. As far as I can tell, it’s not. – Manngo Oct 10 '16 at 09:07
  • True story, the heading of the question is not quiet matching. In deed on the MDN page you cannot really get a final overview of compatibility, I just tested if it is available withing IE 11 and it is. – bash0ne Oct 10 '16 at 09:16