DOM Selectors for multiple elements

getElementsByClassName

const items = document.getElementsByClassName('collection-item');

// Show all items
console.log(items);

// Show only the first index
console.log(items[0]);

// Change the color of first item
items[0].style.color = 'red';

// Change the text of index 3
items[3].textContent = 'Hello';

getElementsByTagName

The Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name.

let lis = document.getElementsByTagName('li');
console.log(lis);
console.log(lis[0]);

// Convert HTML Collection into array

lis = Array.from(lis);

lis.reverse();

lis.forEach(function(li, index){
  console.log(li.className);
  li.textContent = `${index}: Hello`;
});

console.log(lis);

querySelectorAll

const items = document.querySelectorAll('ul.collection li.collection-item');

items.forEach(function(item, index){
  console.log(li.className);
  item.textContent = `${index}: Hello`;
});

console.log(items);

const liOdd = document.querySelectorAll('li:nth-child(odd)');
const liEven = document.querySelectorAll('li:nth-child(even)');

liOdd.forEach(function(li, index){
  li.style.background = '#ccc';
});

for(let i = 0; i < liEven.length; i++){
  liEven[i].style.background = '#f4f4f4';
}
Was this page helpful?

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *