Reputation:
basically, and in a very schematic way, I need to target the first element who has a specific attribute relative to the element who got the event.
<div data-path="2" class="section">
... Nope.
</div>
<div data-path="1" class="section">
<a data-path="2" class="trigger" href="#">Foo</a>
</div>
<div data-path="1" class="section--2">
... Nope.
</div>
<div data-path="2" class="section--3">
I need to target this one, but not the sections previous to the trigger.
</div>
<div data-path="2" class="section--4">
... Nope.
</div>
I can't figure how to achieve this. It seems to be pretty simple but I'm just stuck on this since two days. I try to play with .next() and .nextUntil() but it doesn't work properly.
Any help are welcome and sorry for my english.
Edit : To be clear, what I need is when a click on the .trigger, I need to target the first next section who has the same data-path attribute, but not the sections before the trigger.
Upvotes: 0
Views: 61
Reputation: 28437
You may want to use the nextAll
to get to the next element which has the same property value and then use the first one out of that:
Demo: http://jsfiddle.net/mUt9H/1/
Relevant Code:
$("a").on("click", function() {
var dp = $(this).data("path");
var txt = $(this).parent().nextAll("div[data-path='" + dp + "']").first().text();
alert(txt);
});
Your trigger is an anchor, so first you need to get to its parent div and then traverse to the next elements. Hence, $(this).parent()...
.
Edit: (regarding your comment)
Just chain a .first()
to the statement and you are good to go.
.nextAll("div[data-path='" + dp + "']").first()...
Upvotes: 1
Reputation: 208002
Try:
$('a.trigger').click(function () {
var target = $(this).parent().nextAll('div[data-path="'+$(this).data('path')+'"]').first();
})
Upvotes: 1