HTML DOM querySelector() Method

The querySelector() returns the first element within the document that matches the specified CSS selector or group of selectors and if no matches were found, then the null value is returned. Also note that the querySelector() will only returns the first element that matches with the with the specified selector. The syntax of querySelector() is as follows :
  element.querySelector(CSS Selector)
Where the CSS Selector(s) 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.

Example :
<html>
<body>
  <p class="para">This is Paragraph One</p>
  <p class="para">This is Paragraph Two</p>
  <p class="para">This is Paragraph Three</p>
  <div class="para">This is the text inside the DIV</div>
  <button onclick="func()">Click Here</button>
  <div id="div1"></div>
  <script>
    function func() {
      var x = document.querySelector('.para').innerHTML;
      document.getElementById('div1').innerHTML = x;
    }
  </script>
</body>
</html>
Output :

This is Paragraph One
This is Paragraph Two
This is Paragraph Three
This is the text inside the DIV



At the above example, the querySelector() grabs the first <P> element.

Next Topic :