Hi everyone,
I recently learned (here on stackoverflow : ) ) that when using jquery every time I write
$("...")
a DOM search is performed to locate matching elements. My question is very simple: how do I efficiently perform a series of actions (using the nice methods of jquery objects) on a DOM element I have located with jquery? Currently, I was doing (eg):
var previousHtml = $("#myDiv").html();
$("#myDiv").addClass("tangoClass");
$("#myDiv").html("bla bla bla");
//...
Basically, I was always referring to the element by writing $("#myDiv"). How can I repeatedly manipulate a DOM element (using jquery functions, rather than vanilla Javascript) in an efficient way? Does the following avoid the costly DOM searches?
var myDiv = $("#myDiv");
var previousHtml = myDiv.html();
myDiv.addClass("tangoClass");
myDiv.html("bla bla bla");
Or should I instead try chaining the jquery calls as much as possible, eg:
var previousHtml = $("#myDiv").addClass("tangoClass").html(); //saves me 1 $("#myDiv") call
$("#myDiv").html("bla bla bla");
Thank you for any insight. : )
lara