In case you are well experienced and are here only for the solution you can use this link.
- How does the class attribute work?
- Other Related Concepts
How does the class attribute work?
The below code is an example of a class attribute.
The syntax is as follows:
var elements = document.getElementsByClassName(name);
Here “name” is the class name you are looking to find and “elements” is a variable that would contain the array of elements.
Code and Explanation:
Let’s take a sample HTML code:
<header> <nav> <ul id="freelancer"> <li class="item">Name</li> <li class="item">Skills</li> <li class="item price">Cost</li> <li class="item">Projects</li> </ul> </nav> </header>
Now since we intend to look for the element in a particular section we first identify the section along with the ID.
let docs = document.getElementByID('#freelancer'); let elements = freelancer.getElementsByClassName('item');
Now ‘elements’ contain the list of elements with the class name ‘item’.
When using the aforementioned method, note that
- If you are trying to get elements with the different class names their names must be separated by whitespace and not a comma.
- Class selectors cannot be used in this method