More getElement methods
Up to this point we only used the getElementById to select elements. Now let's explore a few other methods.
getElementsByClassName
This method selects elements by class. The difference now is that classes are not unique, we can have multiple elements sharing the same class. Therefore, this method will always return an array containing the HTML elements that have that class.
<div class="example">Element #1</div>
<div class="example">Element #2</div>
<div class="example">Element #3</div>
var elements = document.getElementsByClassName("exemplo");
console.log(elements);
// The console will show an array: [ {...}, {...}, {...} ]
// Each of the elements of the array are the HTML elements that share that class
These elements can be accessed by the index, in thsi case [0], [1] and [2]. By using the index, we can manipulate their content:
elements[0].innerHTML = "Changing the text of the first element";
getElementsByTagName
This methods works just like the previous one, but this time we'll select element using the tag name (div, h1, p, img, etc).
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
Paragraph 1
Paragraph 2
Paragraph 3
var paragraphs = document.getElementsByTagName("p");
console.log(paragraphs);
// The console will show an array: [ {...}, {...}, {...} ]
Now, using the index to alter these elements doesn't seem to be very efficient. How can we make changes to all of these elements no matter how many of them exist in the page?
The answer is: Loops! The subject of our next lesson.