JavaScript querySelectorAll() example
by danielkwood
HTML
<html>
<head>
<title>querySelectorAll() method</title>
</head>
<body>
<p class="myClass">This is some text</p>
<p class="myClass">This is some more text</p>
</body>
</html>
JavaScript
/**
The querySelectorAll() method will return a static NodeList. eg. if you add an extra element to a list in the document, the list in NodeList will not change. Items in an HTMLCollection can be accessed by their name, id, or index number.
**/
const nodelist = document.querySelectorAll(".myClass");
for (let i = 0; i < nodelist.length; i++) {
nodelist[i].style.color = "green";
}
/**
The getElementsByClassName() method will return a live HTMLCollection. eg. if you add an extra element to a list in the document, the list in the HTMLCollection will also change. Items in a NodeList can only be accessed by their index number.
**/
var htmlcollection = document.getElementsByClassName("myClass");
for (let i = 0; i < htmlcollection.length; i++) {
htmlcollection[i].style.color = "purple";
}