21

Just a quick example:

<p>
    <span class="example"></span>
    <input type="text" name="e_name" id="e_id />
</p>
<script type="text/javascript">
    $('input').click(function(){
        $(this).parent().children('span').text('Suprise!');
    }
</script>

What can I use instead parent().children()?

I think it's a bit inelegant piece of code. Is any function i.e : $(this).fun('span').text('just better'); ??

Mr Sooul
  • 659
  • 2
  • 9
  • 19
  • Thanks for making a very readable question so I didn't have to click on 3 different answers, not knowing what was inside. – Jason Aug 14 '17 at 20:44

5 Answers5

51
$(this).siblings('span').text('Suprise!');
Christopher Armstrong
  • 7,907
  • 2
  • 26
  • 28
  • 1
    I definitely like `.siblings`, hadn't even thought of that function, great answer. – Jeremy B. May 27 '11 at 18:02
  • 3
    `$(this).siblings()` will ignore itself, so if you want to target children including itself, `parent().children()` is still neat. – WaldenW Apr 13 '17 at 17:35
7

$(this).siblings('span').text('Surprise!');

Would be the equivalent without traversing up the DOM and then back down (I mean, it still does it, but at least you're not doing it manually).

rockerest
  • 10,412
  • 3
  • 37
  • 67
4

Slightly more elegant is .prev()

$(this).prev('span').text('Surprise!');

you can read more about it here: Prev

edit: read the markup backwards, prev is better, not next.

Jeremy B.
  • 9,168
  • 3
  • 45
  • 57
1

try this:

$(this).prev('span').text('Surprise!');
drudge
  • 35,471
  • 7
  • 34
  • 45
1
$("span.example",$(this).parent()).text('Suprise!');
Ryan Olds
  • 4,847
  • 28
  • 24