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()
Written by Widy Graycloud
Related protips
3 Responses
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');
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