dev-resources.site
for different kinds of informations.
querySelector vs querySelectorAll in javascript
Published at
10/16/2024
Categories
javascript
webdev
beginners
Author
sagar
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.
Articles
12 articles in total
querySelector vs querySelectorAll in javascript
currently reading
Best Way to add Javascript file in HTML
read article
let, const , var difference in Javascript?
read article
forEach vs map method javascript
read article
What are AEM Components?
read article
4 ways to iterate over “objects” in javascript
read article
Hoisting in javascript ?
read article
“==” and “===” difference in javascript
read article
Common JavaScript "event Handler" Mistake
read article
What is Adobe Experience Manager(AEM) & it's Features
read article
What is CMS (Content Management System)?
read article
Clousers in Javascript?
read article
Featured ones: