Blog

querySelector() in JS

QuerySelector and querySelectorAll:

querySelector` and querySelectorAll are both methods available in JavaScript for selecting elements from the DOM (Document Object Model) based on CSS selectors.

 

1. **querySelector**:

– This method returns the first element that matches a specified CSS selector within the document.

– If no matching element is found, it returns `null`.

– Example:

 

const element = document.querySelector(‘.myClass’);

 

// This will select the first element with the class ‘myClass’

 

2. **querySelectorAll**:

– This method returns a NodeList representing a list of the document’s elements that match the specified group of selectors.

– It returns an empty NodeList if no matches are found.

– Example:

 

const elements = document.querySelectorAll(‘p’);

// This will select all <p> elements in the document

 

**Usage:**

– Both `querySelector` and `querySelectorAll` can accept any CSS selector as their argument.

– They can be used to target elements based on their tag name, class, ID, or other attributes.

– These methods are commonly used for DOM manipulation and event handling in JavaScript.

 

**Note:**

– `querySelector` returns only the first matching element, even if there are multiple matches.

– `querySelectorAll` returns a NodeList, which is similar to an array but does not have array methods like `forEach` or `map`. You may need to convert it to an array using `Array.from()` or using methods like `forEach` on the NodeList directly.

 

Example:

 

 

const paragraphs = document.querySelectorAll(‘p’);

 

// Convert NodeList to Array

const paragraphArray = Array.from(paragraphs);

 

// Loop through each paragraph

paragraphArray.forEach(paragraph => {

console.log(paragraph.textContent);

});

 

 

These methods are quite powerful and widely used in modern web development for their simplicity and flexibility in selecting DOM elements.

Feel free to explore these code example at your own pace.

You will find examples of querySelector and querySelectorAll –> Link

Example of other selectors –> Link

Happy coding!

Afficher plus

Articles similaires

Voir Aussi
Fermer
Bouton retour en haut de la page