Reputation: 267390
I have a href tag, and next to it is a tag. I want to put new text in between the bold tags.
<a href=""></a> <b>old text</b>
So in my click handler, how can I get a reference to the text between the bold tag?
I know there is $(this + b) but how do I make sure it only gets the first and not ALL next items (like in the jquery sample).
Upvotes: 3
Views: 15678
Reputation: 16048
Even though Magnar's answer has been marked as the accepted one, it doesn't actually answer the original question (necessarily). That's a problem when reaching this question from a search. Maybe the question needs to be reworded. Anyway, my point is that this will fail if there's another element in between 'a' and 'b'. To really match the 'first, next' element, use:
$('a').nextAll('b:first')
Note that Tim Büthe's answer is also incorrect (it could match a previous sibling).
Upvotes: 24
Reputation: 115016
Just to add, keep all of these in your toolbox, they are all very handy at traversing and they all can accept selectors (#myid, .myclass, etc) and filters (:visible, :first, :odd, etc)
.parent()
.sibling()
.children()
.next()
.prev()
Upvotes: 2
Reputation: 63814
You also could do:
$(this).siblings(":first").text("Something new");
Upvotes: 5
Reputation: 28830
Get the b-tag with:
$(this).next();
Get the text inside the b-tag with:
$(this).next().text();
And set the text inside the b-tag with:
$(this).next().text("Something new");
Upvotes: 8