Reputation: 5598
How can I make a function for one element, like the each()
does it for multiple elements?
What I want to do, (just for the sake of the example)
$(".element").each(function () {
var height = $(this).height();
$(this).css("bottom", "-" + height + "px");
});
Should I just use the Each()
or should I use one()
?
Upvotes: 0
Views: 78
Reputation: 123377
each()
will works fine also for collections with one element only, but in this case it is not really necessary and for one element introduces only overhead so it's better simply write
var height = $(".element").height();
$(".element").css("bottom", "-" + height + "px");
also note that one()
is not an alternative because its purpose is to attach an handler that has to be called one time only
Upvotes: 1
Reputation: 4696
jQuery each will work perfectly with just the one element in it. So you can go ahead and use .each safely
Upvotes: 0
Reputation: 406
Just call the .css function if you only want to do it once. You can pass an anonymous function as the second paramter in order to do what you're trying to do.
Just remember that this will still do the action to every element that matches your selector. If you only want to apply this to one element, you need to be more specific with your selector.
$(".element").css("bottom", function() {
return "-" + $(this).height() + "px");
});
Upvotes: 1
Reputation: 731
like this?
$(".element").css("bottom", "-" + $(this).height() + "px");
It doesn't need to be in a function
Upvotes: -1