For an DIV element, I'm wondering which of these selectors likely to be faster
$("#ELEMENT_ID")
$('div[id="ELEMENT_ID"]')
is there any difference in performance between using the DIV id only or limiting search to DIV elements only with its ID?
For an DIV element, I'm wondering which of these selectors likely to be faster
$("#ELEMENT_ID")
$('div[id="ELEMENT_ID"]')
is there any difference in performance between using the DIV id only or limiting search to DIV elements only with its ID?
or limiting search to DIV elements only with its ID?
Please note that IDs are unique, so if you are using one ID on more than one element, that is the wrong thing to do.
div[id="ELEMENT_ID"]
and even div#ELEMENT_ID
are generally superfluous, unless you are including a stylesheet across multiple pages, and different pages use the one ID for different elements. Doing that probably isn't a good idea though, as it will probably confuse someone reading the code.
Checking on jsPerf shows that just the id selector is much faster. http://jsperf.com/id-vs-data-id/4
For #ID
and div#ID
selectors, jQuery mentiones that:
For id selectors, jQuery uses the JavaScript function document.getElementById(), which is extremely efficient. When another selector is attached to the id selector, such as h2#pageTitle, jQuery performs an additional check before identifying the element as a match.
For div[ID=something]
selector I am not really sure but I doubt if it would be any faster than #ID
. I would run a performance benchmark and check the results.
PS: there is an interesting note on jQuery ID selector page:
As always, remember that as a developer, your time is typically the most valuable resource. Do not focus on optimization of selector speed unless it is clear that performance needs to be improved.