What is the difference between $('#<%=lblName.ClientID%>')
and $("[id$=lblName]")
?
jQuery selectors allow you to select and manipulate HTML element(s). jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
"$("div p")" Selects all elements matched by <div> that contain an element matched by <p>.
So far we have covered only three standard jQuery Selectors.
Class selectors are the slowest selectors in jQuery.
$('#<%=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
.
$('#<%=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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With