DEV Community

Cover image for querySelector vs querySelectorAll in javascript
sagar
sagar

Posted on

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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.

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

Top comments (0)

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay