Vanilla Javascript basics; Selecting elements based on id or class

Doing vanilla Javascript selecting or setting elements with their id or class name.

Selecting

Selecting a HTML element with its id with getElementById():

document.getElementById("theId");

Selecting an element based on the class name with getElementByClassName()

document.getElementByClassName("class-name");

This returns an array that you can use indices with.

Selecting an element that has class orange inside an element with the id of square:

document.getElementById("square").getElementsByClassName("orange");

Checking if has class

How to check if an element has a class name. This example is checking the element with the id statusText for the class blue:

document.getElementsByClassName("statusText").classList.contains("blue");

This returns true on a result that does have the class and false for when the element does not contain the class.

Checking if id found

Doing a check to see if an id is found or exists:

if(document.getElementById("theId")){
  //Element exists
} else {
 //Element does not exist
}