HTML - DOM querySelector() Method



The HTML DOM querySelector() method allows you to select and access the first HTML element that matches a given CSS selector(s) within the document.

The CSS selectors are used to find or select elements in a document that you want to style or manipulate. For example, you can use IDs, class names, and various other selectors to target specific elements.

Syntax

Following is the syntax of the HTML DOM querySelector() method −

element.querySelector(CSS_selectors);

Parameters

This method accepts a single parameter as mentioned below −

Parameter Description
CSS_selectors A string that defines the type of element you want to select. It can be Id, class, type of elements(like <div>, or <p>) ,or even specific attributes and their values.

Return Value

This method returns the first HTML element that matches a given CSS selector. If no matching element is found, it returns 'null'.

Example 1: Applying Highlight Class to Selected Element

The following is a basic example of the HTML DOM querySelector() method. It adds a "highlight" class to the matched paragraph (<p>) element when the button is clicked −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM querySelector() Method</title>
<style>
   .highlight {
      background-color: lightblue;
   }
   button{
      margin: 5px 0px;
      padding: 8px;
   }
</style>
</head> 
<body>
<p>Selects the first element that matches the given CSS selector</p>
<h4>This is a heading</h4>
<p>This is a paragraph.</p>
<p class="hi">This is another paragraph with class="hi".</p>
<div>This is a div element.</div>
<button onclick="applyHighlight()">Apply Highlight</button>
<script>
function applyHighlight() {
    // Selecting the element with class "hi"
    const hele = document.querySelector('.hi');
    // Applying bold font weight and highlight 
    hele.style.fontWeight = 'bold';         
    hele.classList.add('highlight');      
    // Creating a new paragraph to display the action
    const resp = document.createElement('p');
    resp.textContent = 'Applied bold font weight to element with ' + 'class "highlight".'+ '.highlight';
    document.body.appendChild(resp);
}
</script>
</body>
</html>

Example 2: Selects and Displays the Element Text

This example shows the usage of the querySelector() method by selecting the first <p> element in the document; it then displays the text content of that paragraph as output −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM querySelector() Method</title>   
<style>
   .highlight {
       background-color: yellow;
   }
   button{
       margin: 5px 0px;
	   padding: 8px;
   }
</style>
</head>
<body> 
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p class="highlight">This is another paragraph with class="highlight"</p>
<div>This is a div element.</div>
<button onclick="showOutput()">Show Output</button>
<script>
   function showOutput() {
      // Selecting the first <p> element
      const firstP = document.querySelector('p');
      // Creating a new paragraph to display the result
      const resultP=document.createElement('p');
      resultP.textContent = "Selected paragraph text: "+
      "It selects the first element that matches " + 
      "the specified CSS selector ";
      // Displaying the result in a clean way
      document.body.appendChild(resultP);
   }
</script>
</body>
</html>

Example 3: Selecting and Changing the Text Content

In the example below, the querySelector() method selects a <div> element and modifies it with new text content when a button is clicked −

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM querySelector() Method</title>
<style>
   button{
      margin: 5px 0px;
      padding: 8px;
   }
</style>
</head>
<body>
<p>Selecting and Changing Text Content</p> 
<div id="con">Original text content.</div>
<button onclick="changeContent()">Change Content</button>
<script>
   function changeContent() {
      const cele = document.querySelector('#con');
      // Changing text content of selected element
      cele.textContent = 'Updated text content!';
      // Creating a  paragraph for displaying action
      const resp = document.createElement('p');
      resp.textContent = 
      'Changed text content of element with ID "con".';
      
      // Displaying the result in a clean way
      document.body.appendChild(resp);
   }
</script>
</body>
</html>

Example 4: Adding EventListener on Selected Element

The following example shows how to use the querySelector() method to select an element and add an event listener dynamically −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM querySelector() Method</title>
<style>
   button{
      margin: 5px 0px;
      padding: 8px;
   }
</style>
</head>
<body>
<p>Adding Event Listener on selected element...</p>  
<button id="myButton">Click Me!</button>
<div id="output"></div>  
<script>
   document.addEventListener('DOMContentLoaded',
   function() {
      const b=document.querySelector('#myButton');
      const op = document.querySelector('#output');
      b.addEventListener('click', function() { 
         output.innerHTML = '';
         const msg = document.createElement('p');
         msg.textContent = 'Button clicked!';
         op.appendChild(msg);
      });
   });
</script>
</body>
</html>

Example 5: Selecting and Modifying Form Elements

This example shows how the querySelector() method selects a form element and displays their values in an output panel −

<!DOCTYPE html>
<html lang="en">
<head> 
<title>HTML DOM querySelector() Method</title>
<style>
   button{
      margin: 5px 0px;
      padding: 8px;
   }
</style>
</head>
<body>
<p>Selects the form elements and modifies their values...</p> 
<form id="myForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<br><br>
<button type="button"onclick="submitForm()">Submit Form</button>
</form>
<div id="output"></div> 
<script>
   function submitForm() {
      const form=document.querySelector('#myForm');
      const uin = form.querySelector('#username');
      const pin = form.querySelector('#password');
      // Displaying form data in the output panel
      const op = document.querySelector('#output');
      op.innerHTML = `<p>Username: 
      ${uin.value}</p><p>Password: 
      ${pin.value}</p>`;
   }
</script>
</body>
</html>

Example 6: Selecting and Modifying the Selected Table Row

In the following example, the table rows are modified using the querySelector() method. It adds the "highlight" class to the row selected by the youngest person −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM querySelector() Method</title>
<style>
   button{
      margin: 5px 0px;
      padding: 8px;
   }
   .highlight {
      background-color: yellow;
   }
</style>
</head>
<body>
<p>Selects and adds highlight class on selected table row..</p> 
<table id="myTable" border="1">
   <thead>
   <tr>
      <th>Name</th>
      <th>Age</th>
   </tr>
   </thead>
   <tbody>
   <tr>
     <td>John</td>
     <td>25</td>
   </tr>
   <tr>
      <td>Jane</td>
      <td>30</td>
   </tr>
   </tbody>
</table>
<button onclick="highlightYoungest()">Highlight Youngest</button>
<script>
   function highlightYoungest() {
      const t=document.querySelector('#myTable');
      const r = t.querySelectorAll('tbody tr');
      
      // Finding the youngest person
      let youngestAge = Infinity;
      let youngestRow = null;
      
      r.forEach(row => {
         const age = parseInt(row.querySelector
         ('td:nth-child(2)').textContent);
         if (age < youngestAge) {
            youngestAge = age;
            youngestRow = row;
         }
      }); 
      youngestRow.classList.add('highlight');
      //creates new paragraph to display the result
      const rp = document.createElement('p');
      rp.textContent="Highlighted the youngest " + "person (Age: ${youngestAge}) in the table.";
      // Displaying the  in a clean way
      document.body.appendChild(rp);         
   }
</script>
</body>
</html>

Example 7: Controls Visibility of Div Element

The example below controls the visibility of an element by using the querySelector() method. The <div> element becomes visible when the button is clicked −

<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML DOM querySelector() Method</title>
<style>
   .hidden {
       display: none;
   }
   button{
      margin: 5px 0px;
      padding: 8px;
  }
</style>
</head>
<body>
<p>Controls the visibility of a <div> element...</p>
<button onclick="toggleVisibility()">Control Visibility</button>
<div id="myDiv">
<p>Click the button to hide me!</p>
</div>
<script>
   function toggleVisibility() {
      const d=document.querySelector('#myDiv');
      d.classList.toggle('hidden');
   }
</script>
</body>
</html>

Supported Browsers

Method Chrome Edge Firefox Safari Opera
querySelector() Yes 4.0 Yes 8.0 Yes 3.5 Yes 3.2 Yes 10.0
html_dom_element_reference.htm
Advertisements