jQuery what instead $(this).parent().children()

56,080

Solution 1

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

Solution 2

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

Solution 3

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.

Solution 4

try this:

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

Solution 5

$("span.example",$(this).parent()).text('Suprise!');
Share:
56,080
Mr Sooul
Author by

Mr Sooul

Updated on May 28, 2020

Comments

  • Mr Sooul
    Mr Sooul almost 4 years

    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'); ??

  • Jeremy B.
    Jeremy B. almost 13 years
    I definitely like .siblings, hadn't even thought of that function, great answer.
  • WaldenW
    WaldenW about 7 years
    $(this).siblings() will ignore itself, so if you want to target children including itself, parent().children() is still neat.