Episode 3 of 18

Get Elements By Class or Tag

Select multiple elements using getElementsByClassName and getElementsByTagName — work with HTMLCollections of matching elements.

Get Elements By Class or Tag

Unlike IDs, classes and tags can apply to many elements. getElementsByClassName and getElementsByTagName return HTMLCollections — live lists of all matching elements.

getElementsByClassName

<p class="message">First message</p>
<p class="message">Second message</p>
<p class="message">Third message</p>

<script>
    var messages = document.getElementsByClassName('message');
    console.log(messages);        // HTMLCollection(3)
    console.log(messages.length); // 3
    console.log(messages[0]);     // First <p> element
    console.log(messages[1].textContent); // "Second message"
</script>

getElementsByTagName

var paragraphs = document.getElementsByTagName('p');
console.log(paragraphs);        // HTMLCollection of all <p> elements
console.log(paragraphs.length); // Number of paragraphs

var listItems = document.getElementsByTagName('li');
console.log(listItems[0].textContent);

HTMLCollection

PropertyDescription
.lengthNumber of elements in the collection
[index]Access an element by its position (0-based)
LiveAutomatically updates if the DOM changes
Not an arrayCannot use forEach, map, filter directly

Looping Through Collections

var messages = document.getElementsByClassName('message');

// for loop (works on HTMLCollections)
for (var i = 0; i < messages.length; i++) {
    console.log(messages[i].textContent);
}

// Convert to array first for forEach
var messagesArray = Array.from(messages);
messagesArray.forEach(function(msg) {
    console.log(msg.textContent);
    msg.style.color = 'blue';
});

Key Takeaways

  • getElementsByClassName and getElementsByTagName return HTMLCollections
  • HTMLCollections are live — they update automatically when the DOM changes
  • Access elements by index: collection[0]
  • Convert to an array with Array.from() to use array methods like forEach