jQuery Selector for server side control

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

$('#<%=lblName.ClientID%>') will find an element with the id attribute as supplied 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.

Method 2

$('#<%=lblName.ClientID%>') – # is the Id selector used by JQuery to identify the element with id.

$("[id$=lblName]")Will select all the elements with id attribute which ends with lblName

Method 3

First one($('#<%=lblName.ClientID%>')), id selector, will find an element by its ID. That is very fast as it will use native document.getElementById

Second one, Attribute Ends With selector, works in different way. In IE, for instance, it will get all elements and test ID of each element if it ends with provided value (or something similar). That is much slower. In newer browsers there is querySelectorAll which possibly will be used to find an element by that selector, but I’m not sure if it is supported by that functions (Well, here it is defined like vailid css3 so suppose modern browsers will support ends with selector in querySelectorAll).

So, in conclusion, id selector should be faster in any case and much faster in case of old browsers. At the same time, ends with selector allows you to find an element without passing its client ID to browser.

Method 4

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x