Search This Blog

Sunday, May 20, 2012

Avoid jQuery selectors repeatedly



Take a look at below jQuery code. The selectors are used thrice for 3 different operation.
1
$("#myID").css("color", "red");
2
$("#myID").css("font", "Arial");

3
$("#myID").text("Error occurred!");
The problem with above code is, jQuery has to traverse 3 times as there are 3 different statements.But this can be combined into a single statement.
1
$("#myID").css({ "color": "red", "font": "Arial"}).text("Error occurred!"); 
This will ensure that jQuery traverse only once through DOM while selecting the element

No comments:

Post a Comment