Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery newbie: how to efficiently do multiple actions on same DOM element?

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

like image 776
laramichaels Avatar asked Dec 11 '09 17:12

laramichaels


People also ask

What is the fastest way to query Dom?

getElementById is the fastest.

Can we use multiple selectors in jQuery?

jQuery - Multiple Elements SelectorYou can specify any number of selectors to combine into a single result.

How do you target multiple elements in jQuery?

To select multiple elements of an html page using multiple elements selector, we pass the element names inside parenthesis, in double quotes, separated by commas. For example: $(“div, p, h2”) this will select all the div, p and h2 elements of a page.


1 Answers

I also agree that chaining is the best method to use, but something else no one has address here is using .andSelf()(1) and .end()(2) while chaining.

The following adds the "border" class to both the div and the p contained within.

$("div").find("p").andSelf().addClass("border");

Using .end() "resets" the selector

$("div")
  .find("p").addClass("myParagraph").end()
  .find("span").addClass("mySpan");

Update: .andSelf() has been deprecated and essentially renamed to .addBack(), use it in the same manner.

like image 85
Mottie Avatar answered Sep 28 '22 00:09

Mottie