g7ocxa
Last Updated: February 25, 2016
·
1.533K
· grazerc0de

Effective Plain Javascript Selector

In plain javascript we used to select an element like this:

document.getElementById("someElement")

above is for the id

document.getElementsByClassName("someElement")

above is for the class

But don't you know we can select elements effectively like this?


document.querySelector("#someElement")

above for the id


document.querySelector(".someElement")

above for the class

Now our JS code is more flexible than traditional javascript selector
Just by using document.querySelector()

3 Responses
Add your response

12490

What if there is more than one element with same class? You'd have to use querySelectorAll, and loop, just like getElementsByClassName. For id's I don't think it's even worth using querySelector, no real gains there, id's are unique. A better example where querySelectorAll is really useful, querying selectors:

var els = document.querySelectorAll('ul > li a');
over 1 year ago ·
15065
15068

And my test http://jsperf.com/byclassname-vs-queryselectorall

While, surprisingly, querySelector(All) has better support, byId & byClassName are so much faster that I'd try and use them where possible

over 1 year ago ·