Javascript querySelector and querySelectorAll methods

jQuery is one of the most popular Javascript libraries, esp. used for traversing and manipulating DOM elements. Javascript too has few inbuilt methods which can be used to access DOM elements. Two of these popular methods are as following:

a. querySelector

b. querySelectorAll

These methods accept any valid CSS selector as an argument and can be invoked either on document object or any other HTML element object.

When invoked over an element or document with a valid CSS selector, these methods would return descendants which match up the selector. In such a case, querySelector would return a single element object (the first match found), where as, querySelectorAll would return a list of all matching elements.

Initially these methods did not enjoy a good browser support but now they are well supported across all modern browsers and can be used freely.

Even with the presence of these methods, still jQuery is popular for DOM traversal primarily because initially querySelector and querySelectorAll did not enjoy much of cross browser support which was well taken care off by jQuery. This is ofcourse not the case now.

The other reason which makes libraries like jQuery more popular is the presence of other utility functions like map(), filter() etc.. which can be used over elements collections for further processing.

So next time, if there is not much processing required in your application then you may prefer using querySelector or querySelectorAll methods instead of going for jQuery.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s