How to use querySelector In Javascript

This method selects the first element that matches a specified CSS selector. It returns only one element.

Syntax:

document.querySelector('selector')

Example:

HTML
<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width,
                   initial-scale=1.0">
    <title>querySelector Example</title>
</head>
  
<body>
    <div class="gfg">w3wiki</div>

    <script>
        const element = 
        document.querySelector('.gfg');
        element.style.color = "green";
        element.style.textAlign = "center";
        element.style.margin = "30px";
        element.style.fontSize = "30px";
    </script>
</body>
  
</html>

Output:

Output

How to select DOM Elements in JavaScript ?

Selecting DOM (Document Object Model) elements is a fundamental aspect of web development with JavaScript. It allows developers to interact with and manipulate elements on a webpage dynamically. Proper selection of elements is crucial for tasks such as updating content, adding event listeners, or modifying styles.

Below are the approaches to select DOM elements in JavaScript:

Table of Content

  • Using getElementById
  • Using getElementsByClassName
  • Using getElementsByTagName
  • Using querySelector
  • Using querySelectorAll

Similar Reads

Using getElementById

This method selects a single element by its unique ID attribute....

Using getElementsByClassName

This method selects elements based on their class attribute. It returns a collection of elements with the specified class name....

Using getElementsByTagName

This method selects elements based on their tag name. It returns a collection of elements with the specified tag name....

Using querySelector

This method selects the first element that matches a specified CSS selector. It returns only one element....

Using querySelectorAll

Similar to querySelector, but it returns a NodeList containing all elements that match the specified CSS selector....