Hi Folk,
Nowadays, lots of us use jQuery for front-end development and found the bad practice.
i.e. <div> Programming Language </div> <ul id="language"> <li>Basic</li> <li>C++</li> <li>Cobol</li> <li>Java</li> <li>Pearl</li> <li>Python</li> <li>PHP</li> <li>Ruby</li> <li>Scala</li> </ul>
//Bad practice
//Give yellow background to Basic
1) $("#language").children(": first").css({"background-color":"yellow"});
//Change Basic to Q-Basic
2) $("#language").children(":first").html("Q-Basic");
//Adding new language to list
3) $("#language").append("<li>Cold Fusion</li>");
//Good practice
//Cache the language element
var lngObj = $("#language");
//Cache the first children so that it can be reused later on...
var firstChild = lngObj.children(":first"); //There are plenty of ways to get First children..!!
1) PLUS 2)
//This is called chaining(calling more than one methods on single object)
firstChild.css({"background-color":"yellow"}).html("Q-Basic");
3) lngObj.append("<li>Cold Fusion</li>");
//Why it is important
Everytime whenever Jquery selector is created, it needs to traverse/Scan the DOM to find out reference to that element and it costs processing and time so degrade the speed.
Twitter had an issue in past for non responsive UI because of above.
This matters when there are thousand of elements in DOM..!!!!