Does the .add()
method allow selecting multiple objects in one go instead of adding one at a time?
one.add(two).add(three).add(four).on("click", function() { });
The following variables are set in the way they do because each carries a different function.
var one = $("#1"); var two = $("#2"); var three = $("#3"); var four = $("#4");
But what if I want to add an extra function that applies to all of these elements? Do I have to add them one by one?
I know you can select them all using $("#1,#2,#3,#4")
, but I just want to make use of the above variables.
In jQuery, you can select multiple elements by separate it with a comma “,” symbol.
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
I'd prefer this array approach, purely for readability...
$([one, two, three, four]).each(function() { // your function here });
You cannot add multiple objects in one go, for example:
var groupThree = one.add(three, five); // will not work as expected
You could cache the added objects so that you only have to do the add one time - http://jsfiddle.net/X5432/
var one = $("#1"); var two = $("#2"); var three = $("#3"); var four = $("#4"); var five = $("#5"); var groupOne = one.add(two).add(three).add(four); var groupTwo = groupOne.add(five); $('#first').click(function(e){ e.preventDefault(); groupOne.css({'background': '#00FF00'}); }); $('#second').click(function(e){ e.preventDefault(); groupTwo.css({'background': '#FF0000'}); });
But I like the array method better, this is just a different way of thinking about it.
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