Skip to main content

querySelector in JavaScript DOM (Live Playground)

In this tutorial, we will learn how to use the querySelector method in JavaScript to select and manipulate HTML elements using CSS selectors. We'll cover the basics of the method and provide sample code with explanations.

What is querySelector?

The querySelector method is a built-in JavaScript DOM method that allows you to select the first HTML element that matches a specified CSS selector. The method returns the first element that matches the selector or null if no matching element is found. It enables you to access specific elements in your HTML document using more complex and powerful selection criteria than other DOM selection methods.

Sample Code: Using querySelector

Let's say we have the following HTML document:

<!DOCTYPE html>
<html>
<head>
<title>querySelector Example</title>
</head>
<body>
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
<p class="mainParagraph">This is another paragraph with the same class.</p>
</body>
</html>

To use querySelector to select elements, you'll need to include a JavaScript <script> tag in your HTML document. For this example, we will add an inline script, although it's generally recommended to use external JavaScript files for larger projects.

Here's how you can select the first p element with the class "mainParagraph" and change its text content:

<!DOCTYPE html>
<html>
<head>
<title>querySelector Example</title>
</head>
<body>
<h1 class="mainHeading">Welcome to My Web Page!</h1>
<p class="mainParagraph">This is an introductory paragraph.</p>
<p class="mainParagraph">This is another paragraph with the same class.</p>

<script>
// Select the first element with the class "mainParagraph"
var firstMainParagraph = document.querySelector('.mainParagraph');

// Change the text content of the selected element
firstMainParagraph.textContent = 'This paragraph has been updated.';
</script>
</body>
</html>

After running this code, the text content of the first p element with the class mainParagraph will be updated to "This paragraph has been updated.".

Live Playground, Try it Yourself

Conclusion

The querySelector method is a powerful and versatile way to select and manipulate HTML elements using CSS selectors. By mastering this method, you can easily access and modify specific elements in your HTML documents using more complex selection criteria, allowing you to create dynamic and interactive web pages.