Lesson 136 – Complete 2020 Web Development Bootcamp

Lesson 136 – Selecting HTML elements with Javascript allows

The javascript code –

document.getElementByTagName("");

allows you to search through the docment and select the tag name placed inside the parenthesis. You can, for example, select an<li> tag like this –

document.getElementsByTagName("li");

You can select elements by class name with this code –

document.getElementsByClassName("btn");

It is important to remember that because you are using the plural .getElementsByClassName, you will get back an area. This means that even if you only have one “btn” class in your html code you will still get back an array. As a result, the following code will not work to change the color of the “btn” class –

document.getElementsByClassName("btn").style.color = "yellow";

In order to change the color of the “btn” class, you have to select the array item that contains the “btn” class. In this case, as there is only one item that contains the “btn” class, there is only one item in the array and you would select it with “[0]”. So the code to change the color of the “btn” class would be –

document.getElementsByClassName("btn")[0].style.color = "yellow";

You can select items by their id using –

document.getElementById("");

As this method is singular, you only get back one item. You don’t get an array.

You can also select a single item using –

document.querySelector("");

The querySelector method also returns just one item and not an array. You use CSS selectors inside the parenthesis to tell the method what to select. For example –

document.querySelector("h1");

//or

document.querySelector("#title");

With the querySelector method you can combine CSS selectors. So if you want to select an anchor tag within an li element, you can do this –

document.querySelector("li a");

This code –

document.querySelector("li .list");

will only select the first li item with a class of “list” even if there are more than one li items with a class of “list”. If you want to select all of the li items with a class of “list”, you need to use this method –

document.querySelectorALL("li .list");

This method will return an array of all of the li elements with a class of “list”. Accordingly to change one of the list items you have to specify its position in the array. Such as –

document.querySelectorALL("li .list")[1];

The challenge for this lesson was to set the color of an anchor tag within an li element to red. This is the code to do that:

document.querySelector("li a").style.color = "red";

This is a Codeply I created to practice using DOM selectors – Javascript DOM selectors.