Home >Web Front-end >JS Tutorial >querySelector vs querySelectorAll in javascript

querySelector vs querySelectorAll in javascript

Susan Sarandon
Susan SarandonOriginal
2024-10-17 06:29:021037browse

querySelector vs querySelectorAll in javascript

querySelector vs querySelectorAll both are used select and manupulate DOM elements but they have some different behavior

1.querySelector
Returns the first matching element in the DOM that satisfies the CSS selector. If no match is found, it returns null.

<nav>
<!DOCTYPE html>
<html>
<body>
<nav class='nav'>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/python/">Python</a>
</nav>

<script>

const link  = document.querySelector("a")
console.log(link); // <a href="/html/">HTML</a>

</script>

</body>
</html>

in the above code example we can see inside script tag i have selected a tag and we are getting only first one matching element not all.

2.querySelectorAll
Returns all matching elements as a NodeList, which is a collection of elements. If no match is found, it returns an empty NodeList.

<nav>
<!DOCTYPE html>
<html>
<body>
<nav class='nav'>
<a href="/html/">HTML</a> |
<a href="/css/">CSS</a> |
<a href="/js/">JavaScript</a> |
<a href="/python/">Python</a>
</nav>

<script>

const link  = document.querySelectorAll("a")
console.log(link); // // [object NodeList] (4) [<a/>,<a/>,<a/>,<a/>]

</script>

</body>
</html>

in the above code example we can see inside script tag i have selected a tag and we are getting all matching elements as a NodeList.

The above is the detailed content of querySelector vs querySelectorAll in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn