Server-side jQuery selector

What is the difference between $('#<%=lblName.ClientID%>') and $("[id$=lblName]") ?

+6
source share
4 answers

$('#<%=lblName.ClientID%>') will find the element with the id attribute provided by the ClientID property in ASP.Net.

$("[id$=lblName]") will find an element with an id attribute that ends with lblName , for example foo-lblName .

+22
source

$('#<%=lblName.ClientID%>') - # - Id selector used by JQuery to identify an element with an identifier.

$("[id$=lblName]") - Selects all elements with an id attribute that ends with lblName

+2
source

The first ( $('#<%=lblName.ClientID%>') ), the id selector, will find the element by its identifier. This is very fast since it will use native document.getElementById

Second, Attributes end with a selector , works differently. For example, in IE, it will get all the elements and a test identifier for each element if it ends with the provided value (or something similar). This is much slower. Newer browsers have querySelectorAll that will probably be used to find an element with this selector, but I'm not sure if it is supported by these functions (well, here it is defined as vailid css3, so suppose modern browsers will support ends with selector in querySelectorAll).

So in conclusion, the id selector should be faster anyway and much faster with older browsers. At the same time, using the selector, you can find an element without passing its client ID to the browser.

+1
source

Just adding what I found out today, $('#<%=lblName.ClientID%>') will select only one element, however $("[id$=lblName]") will select more than one element, so if you have the same identifier assigned to more than one element, and if you want to intersect all of them, then the first case will not work properly.

0
source

All Articles