How do you use jQuery selector? Do you select DOM element with Tag name and ID or only with ID? Which is the efficient way to select elements? After reading this post, you will learn what is the best way to select DOM element when you know the ID of the element.
Let's say you have following HTML.
Always try to use ID as selector as they are very fast.When IDs are used as selector then jQuery internally makes a call to getElementById() method of Java script which directly maps to the element.
In this second statement, we are adding one more layer of searching for selecting div with "select-me" id. We are telling jQuery to iterate through all div element and which has "select-me" id. And in first case, we are directly telling jQuery to return the element with id. So, the first statement is much faster and efficient. You can see the performance result in below image.
Feel free to contact me for any help related to jQuery, I will gladly help you.
Let's say you have following HTML.
<div> <div id="select-me"> </div> <div> Dont worry about selecting me </div> <p> I am just in here for more code </p> </div>Now, there are 2 ways to select the div element with id="select-me". First is,
$("#select-me");And Second is,
$("div#select-me");Both the statement will return you div with id "select-me". But doesn't mean that both statement are equal. The answer is "NO".
Always try to use ID as selector as they are very fast.When IDs are used as selector then jQuery internally makes a call to getElementById() method of Java script which directly maps to the element.
In this second statement, we are adding one more layer of searching for selecting div with "select-me" id. We are telling jQuery to iterate through all div element and which has "select-me" id. And in first case, we are directly telling jQuery to return the element with id. So, the first statement is much faster and efficient. You can see the performance result in below image.
Check Performance Test
No comments:
Post a Comment