Javascript:QuerySelector

JAVASCRIPT


Query Selector All

// Class Selector , get all elements with class example

var x = document.querySelectorAll(".example");


// Get all <p> elements in the document
var x = document.querySelectorAll("p");

// Set the background color of the first <p> element
x[0].style.backgroundColor = "red"; 


// Get all <p> elements in the document with class="example"
var x = document.querySelectorAll("p.example");

// Set the background color of the first <p> element with class="example" (index 0)
x[0].style.backgroundColor = "red"; 

var x = document.querySelectorAll(".example").length;



Set the border of all <a> elements in the document that have a "target" attribute:

var x = document.querySelectorAll("a[target]");
var i;
for (i = 0; i < x.length; i++) {
  x[i].style.border = "10px solid red";
}


Set the background color of all <p> elements in the document:

var x = document.querySelectorAll("p");
var i;
for (i = 0; i < x.length; i++) {
  x[i].style.backgroundColor = "red";
}







Set the background color of every <p> element where the parent is a <div> element:

var x = document.querySelectorAll("div > p");
var i;
for (i = 0; i < x.length; i++) {
  x[i].style.backgroundColor = "red";
}





Set the background color of all <h2>, <div> and <span> elements in the document:

var x = document.querySelectorAll("h2, div, span");
var i;
for (i = 0; i < x.length; i++) {
  x[i].style.backgroundColor = "red";
}