Popular javascript selector methods

Saibal Roy • January 18, 2020

javascript productivity-tips

Hello Everyone!

Welcome to my website and this is Saibal with yet another post to share my knowledge with you all.

Following javascript selector methods proves to be quite handy working with vanilla javascript or building your own javascript library like feedback form component to be used with added to websites to collect data.

For selecting single element:

element = document.querySelector(selector);

For selecting multiple elements:

elementList = document.querySelectorAll(selectors);

Great, but here comes the tricky part when using querySelectorAll returns a NodeList object, which doesn't provide any array functions like push, map, forEach which makes working at ease. Now there's a cool trick to achieve it.

elementList = Array.from(document.querySelectorAll(selectors));

Now, the NodeList gets transformed to an array which works great and make use of the array functions.

There are other cool functions that are worth checking and useful in terms of performance and more specific too.

Check out how getElementById works

Check out how getElementsByClassName works

Check out how getElementsByName works

Check out how getElementsByTagName works

Happy learning folks!