If an element exists anywhere in the DOM, do something

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