curly_brackets
curly_brackets

Reputation: 5598

Similar to each() but only for one selector

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

Answers (4)

Fabrizio Calderan
Fabrizio Calderan

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

Jibi Abraham
Jibi Abraham

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

sngregory
sngregory

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

Hank
Hank

Reputation: 731

like this?

$(".element").css("bottom", "-" + $(this).height() + "px");

It doesn't need to be in a function

Upvotes: -1

Related Questions