Vanilla Javascript basics; Selecting elements based on id or class

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


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


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


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:


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:


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:

  //Element exists
} else {
 //Element does not exist