Others



querySelector() Method in JavaScript


The querySelector() method is used to return the first matching Element in the document. We can select element by Tag Name, id, Class name and etc.

Syntax
document.querySelector("#id"); //Returns the first matching element with id. 
document.querySelector(".cls"); //Returns the first matching element with class name. 
document.querySelector("p"); //Returns the first matching element with tag name.
document.querySelector("input[type='text']"); //Returns the first matching input with type='text'.

The following example shows, how to select element with id using querySelector() method.

Example
<p><input type='text' id='num' value='10'></p>
<input type='button' value='click' onclick='get_val()'>
<p id='output'></p>
<script>
  function get_val(){
    var a=document.querySelector("#num").value;
    document.querySelector("#output").innerText="Entered Values is "+a;
  }
</script>
Try it Yourself

The following example shows, how to select element with class name using querySelector() method.

Example
<ul>
  <li class='items'>List Item 1</li>
  <li class='items'>List Item 2</li>
  <li class='items'>List Item 3</li>
  <li class='items'>List Item 4</li>
</ul>
<input type='button' value='click' onclick='get_item()'>
<p id='output'></p>  
<script>
  function get_item(){
    var a=document.querySelector(".items").innerText;
    document.querySelector("#output").innerText=a;
  }
</script>
Try it Yourself
Methods Description
getElementById() Used to return the matching element with given ID name.
getElementsByClassName() Used to return all matching elements with the given class name.
getElementsByTagName() Used to return all matching elements with the given tag name.
getElementsByName() Used to return all matching elements with the given name (name attribute).
queryselectorAll() Used to return all matching Elements.