Reputation: 404
This is my code:
$(document).ready(function() {
if ($(".box1").next().is(".box2")) {
$(this).css("margin", "0");
}
});
My .box1
div has a style of margin: 50px
.
To summarize, what I want: If a .box2
div appears after a .box1
div, then my .box1
div now has a margin of 0px. I have 10 .box1
divs and not all .box1
divs have a .box2
div appearing after them. I only want the .box1
divs with a .box2
div appearing after them to have margin:0px
. I don't know how to achieve this with my current code using the $(this) keyword. Please help, thank you
Upvotes: 1
Views: 51
Reputation: 224942
Here’s another possible approach, which should have similar performance if there are similar numbers of .box1
and .box2
:
$(".box2").prev(".box1").css("margin", "0");
Upvotes: 4
Reputation: 781096
You haven't assigned anything to this
, since the code isn't in an event handler (well, technically ready
is considered an event in jQuery, but it's not really helpful in this case).
You can use .each()
to loop over all the elements of a selection, then this
will be the current element in the iteration.
$(document).ready(function() {
$(".box1").each(function() {
if ($(this).next().is(".box2")) {
$(this).css("margin", "0");
}
});
});
Upvotes: 3