If an element exists anywhere in the DOM, do something

I want to check if an element exists anywhere in the entire DOM and if so, do something (either with that element or with another).

  • I don’t think document.querySelector() is what I need because if it fails than all code under it might malfunction (thus, an if-else statement might be pointless)
  • I don’t think if (document.body.contains(ELEMENT)) {} is what I need because it doesn’t search in the entire DOM (rather, only on direct children of body)

Update

I am looking for a specific element.

Are you looking for a specific element, or a type of element? You just have to handle the object appropriately.

If you have an id, you could use getElementById

If (document.getElementById("demo") != null) {
  // exists, do something...
}

if you’re looking for a type of element, you could use get

if (document.getElementsByTagName("li").length > 0) {
   // exists, do something
}

Or for something more complex, you could use query

if (document.querySelector("p.x2") != null) {
 // exists, do something
}
2 Likes

I second the use of querySelector these days. It is highly versatile and you can just check if what you assign is truthy. If the element was found then it passes the test. if the element wasn’t found then the falsy nature of the variable will help you avoid any other troubles.

var x2 = document.querySelector("p.x2");
if (x2) {
    doStuffWith(x2);
}

or

var x2 = document.querySelector("p.x2");
if (!x2) {
    return;
}
doStuffWith(x2);
1 Like

Thanks Paul,

As far as I know trying to select an element which doesn’t exist (say, due to a mistake) can cause any code after that command to “break” hence I would do something like:

if (document.querySelector("#x") !== null) {
  document.querySelector("#x").remove();
}

A minor problem for me here is that (maybe) variables can’t be used in this way, so we have to multiply the querySelector.

Paul’s version does the same as yours with the exception of it being stored to an object, which means the DOM only has to be traversed once. It’s more efficient that way.

1 Like

That is incorrect. Code from my above post where the element doesn’t exist is guaranteed to not break at all in any way due to the non-existing element.

3 Likes

Well, than I assume I meant only to code dependent on the selection of a currently nonexistent element.

:slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.