Check If Element Exists in Javascript

In this post, we check if a certain element exists in the DOM. We have many methods in Javascript to do this task.

Method 1: document.querySelector()

The Document method querySelector() returns the first Element within the document that matches the specified selector.  If no matches are found, null is returned.

if (document.querySelector("#divID")) {
  console.log("Element exists!");
} else {
  console.log("Element DOES NOT exist!");
}

Method 2 : document.getElementById()

Method getElementById() returns an Element an object representing the element whose id property matches the specified string.

IDs are required to be unique and case sensitive

if (document.getElementById("MyDivID")) {
  console.log("Element exists!");
} else {
  console.log("Element DOES NOT exist!");
}

Method 3: document.getElementsByName()

The getElementsByName() method of the Document object returns a NodeList Collection of elements with a given name the attribute in the document.

let elements = document.getElementsByName("name");
if (elements.length) {
  console.log("At least one element exists!");
} else {
  console.log("Element DOES NOT exist!");
}

Example:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Example: using document.getElementsByName</title>
  </head>
  <body>
    <input type="hidden" name="up" />
    <input type="hidden" name="down" />
  </body>
</html>

Script:

var up_names = document.getElementsByName("up");
console.log(up_names[0].tagName); 

Result:

 "INPUT"

Method 4: document.getElementsByClassName()

The getElementsByClassName method of Document interface returns an array-like object of all child elements which have all of the given class name(s).

var elements = document.getElementsByClassName(names); // or:
var elements = rootElement.getElementsByClassName(names);