tags:

views:

1886

answers:

4

Hi,

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).

+3  A: 

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");
Magnar
+2  A: 

You also could do:

$(this).siblings(":first").text("Something new");
Tim Büthe
+1  A: 

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()
Jon Erickson
A: 

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).

Bobby Jack