querySelectorAll() Method in JavaScript

Views: 1029
Comments: 1
Like/Unlike: 2
Posted On: 14-Sep-2017 21:08 

Share:   fb twitter linkedin
Kailash...
206 Points
23 Posts
Definition
 
The querySelectorAll() method returns all elements in the document that matches a specified selector(s), as a static NodeList object. The NodeList object states a collection of nodes. It can be accessed by index numbers. The index starts at 0.
 
Syntax
 
document.querySelectorAll(CSS selectors)
 
Parameter (CSS selectors)
 
Type: String
Description: It's Required. Specifies one or more CSS selectors to match the element. These are used to select HTML elements based on their id, classes, types, attributes, values of attributes, etc. Multiple selectors can be separate commas.
 
Examples
 
I) Get all <p> elements in the document, and set the background color to "red" of the first <p> element (index 0):
 
// Get all <p> elements in the document
var pElements = document.querySelectorAll("p");

// Set the background color of the first <p> element
pElements[0].style.backgroundColor = "red"; ​
 
II) Find out how many elements with class="example" there are in the document (using the length property of the NodeList object):
 
var elementCount = document.querySelectorAll(".example").length;
 
III) Set the background color to "red" of all elements in the document with class="example":
 
 
var myElements = document.querySelectorAll(".example");
var i;
for (i = 0; i < myElements.length; i++) {
    myElements[i].style.backgroundColor = "red";
}
 
IV) Set the border of all <a> elements in the document that have a "target" attribute:
 
var myElements = document.querySelectorAll("a[target]");
var i;
for (i = 0; i < myElements.length; i++) {
    myElements[i].style.border = "5px solid red";
}​
  
Conclusion
Hope above descriptions are useful to understand 'querySelectorAll()' JavaScript method.
1 Comments
great...

andro
12-Jun-2018 at 19:29
 Log In to Chat