I recently found out (here on stackoverflow :)) that when using jquery every time I write
$("...")
a DOM search is performed to find matching items. My question is very simple: how to efficiently execute a series of actions (using beautiful jquery object methods) on the DOM element that I found with jquery? I am currently doing (for example):
var previousHtml = $("#myDiv").html(); $("#myDiv").addClass("tangoClass"); $("#myDiv").html("bla bla bla");
Basically, I always referred to an element, writing $ ("# myDiv"). How can I repeatedly manipulate a DOM element (using jquery functions, not vanilla Javascript) in an efficient way? Does the following mean to avoid expensive DOM searches?
var myDiv = $("#myDiv"); var previousHtml = myDiv.html(); myDiv.addClass("tangoClass"); myDiv.html("bla bla bla");
Or should I instead try to combine the jquery calls as much as possible, for example:
var previousHtml = $("#myDiv").addClass("tangoClass").html(); //saves me 1 $("#myDiv") call $("#myDiv").html("bla bla bla");
Thank you for understanding.:)
lara
javascript jquery jquery-selectors
laramichaels
source share