js

Sunday, April 21, 2024

Javascript: Explain querySelector() in Javascript

 Q. Explain querySelector() in Javascript

querySelector() is a JavaScript method that allows you to select and retrieve elements from the DOM (Document Object Model) using CSS-style selectors. It returns the first element within the document that matches the specified selector, or null if no matches are found.

Here's how you use it:

javascript
const element = document.querySelector(selector);
  • selector is a CSS selector string that specifies the criteria for selecting the desired element(s). It could be an element name (e.g., "div"), a class (e.g., ".classname"), an ID (e.g., "#id"), or any other valid CSS selector.

  • element will hold a reference to the first DOM element that matches the given selector. If there are multiple matching elements, querySelector() returns only the first one.

For example:

html
<!DOCTYPE html>
<html>
<head>
<title>querySelector Example</title>
</head>
<body>
<div id="container">
<p class="text">First paragraph</p>
<p class="text">Second paragraph</p>
<p class="text">Third paragraph</p>
</div>
<script>
// Select the first paragraph element with the class "text"
const firstParagraph = document.querySelector('.text'); console.log(firstParagraph.textContent);
// Output: "First paragraph"
</script>
</body>
</html>

In this example, querySelector('.text') selects the first paragraph element with the class "text", which is "First paragraph", and assigns it to the firstParagraph variable.

 

No comments:

Post a Comment

SEBA HSLC Question Paper Assamese 2022