DOM Selectors for Multiple Elements in JavaScript: Methods and Usage
☰Fullscreen
Table of Content:
// document.getElementsByClassName const items = document.getElementsByClassName('collection-item') console.log(items); console.log(items[0]); items[0].style.color = 'red'; items[3].textContent = 'Hello'; const listItem = document.querySelector('ul').getElementsByClassName('collection-item'); // document.getElementsByTagName const lis = document.getElenetByTagName('li') console.log(lis); console.log(lis[0]); lis[0].style.color = 'red'; lis[3].textContent = 'Hello'; // 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); // document.querySelectorAll const item = document.querySlectorAll('ul.collection li.collection-item'); items.forEach(function(item, index) { console.log(li.ClassName); item.textContent = `${index}: Hello`; }); 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'; } console.log(items);