Ads by ProfitSence
Close

querySelectorAll JavaScript Code Example

Last Updated on Wednesday 5th Oct 2022

The most versatile method, elem.querySelectorAll(css) returns all elements inside elem matching the given CSS selector.

  • querySelectorAll returns a list of Nodes.

Example 1

			
					<ul>
  <li>The</li>
  <li>test</li>
</ul>
<ul>
  <li>has</li>
  <li>passed</li>
</ul>

			
	
			
					let elements = document.querySelectorAll('ul > li:last-child');

for (let elem of elements) {
    alert(elem.innerHTML); // "test", "passed"
}

			
	

Example 2

  • Example with Multiple Events
			
					let items = document.querySelectorAll("li");
for (let i = 0; i < items.length; i++) {
  items[i].addEventListener("mouseout", function () {
    let tagElement = items[i].previousElementSibling;
    tagElement.classList.remove("clsone");
  });
  items[i].addEventListener("mouseover", function () {
    let tagElement = items[i].previousElementSibling;
    tagElement.classList.add("clstwo");
  });
}