Muhammad Mutahar Alam
Muhammad Mutahar Alam

Reputation: 163

jQuery Selector for server side control

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

Upvotes: 7

Views: 25283

Answers (4)

Muhammad Mutahar Alam
Muhammad Mutahar Alam

Reputation: 163

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.

Upvotes: 0

Viktor S.
Viktor S.

Reputation: 12815

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.

Upvotes: 1

Jayendra
Jayendra

Reputation: 52769

$('#<%=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

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

$('#<%=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.

Upvotes: 23

Related Questions