How to query HTML document using CSS selector with Javascript

Query with CSS selector

querySelectorAll(<selector>) gets all of the elements that match the specified CSS selector. The return type is HTMLElement[].

Example


<!DOCTYPE HTML> 
<html> 
<body> 
  <img id="apple" src="apple.png"/> 
  <script> 
    var elems = document.querySelectorAll("p, img#apple") 
    document.writeln(elems.length); 
  </script> 
</body> <!--   w ww .j ava 2  s. c om-->
</html>

Click to view the demo

Query for parents


<!DOCTYPE HTML> 
<html> 
<body> 
  <pre id="results"></pre> 
  <p id="tblock"> 
      This is a HTML document. <!--from  w  w  w  .  j a  va2s.c  o  m-->
      <span id="banana">b</span> 
      <span id="apple">a</span>, 
      <span="orange">C</span="orange"> 
  </p> 
  <script> 
      
      var selElems = document.querySelectorAll("#tblock > span"); 
      document.writeln(selElems.length); 
  </script> 
</body> 
</html>

Click to view the demo

Is querySelectorAll available

The following code if the document object has the querySelectorAll method.


<!DOCTYPE HTML> 
<html> 
<body> 
 <p id="paratext"> 
     This is a test.<!--from  ww w  .  j  av  a  2  s  . com-->
     This is a test.
     This is a test.
     <img src="apple.png" alt="apple"/> 
 </p> 
 <script> 
     var images; 
     if (document.querySelectorAll) { 
         images = document.querySelectorAll("#paratext > img"); 
     } else { 
         images = document.
                     getElementById("paratext").
                     getElementsByTagName("img"); 
     } 
     for (var i = 0; i < images.length; i++) { 
         images[i].style.border = "thick solid black"; 
         images[i].style.padding = "4px"; 
     } 
 </script> 
</body> 
</html>

Click to view the demo





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window