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
getElementById is the fastest.
jQuery - Multiple Elements SelectorYou can specify any number of selectors to combine into a single result.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With