Search code examples
jquerytraversal

Traversing up ( parent ) and then down ( child )


I want to achive something like this

var argument = $(this).parent().parent().parent().prev().child().attr('ctryid');

here is a snip of the section I want to traverse. I want to go from newProvButton to the element with ctryid.

its a mess, im sorry.

enter image description here


Solution

  • You can use closest() to find the related parent element with the given selector. Try this:

    var argument = $(this).closest('.expandListContent').prev().find('.expandListHeaderRow').attr('ctryid');
    

    You should also note that using non-spec attributes in your HTML will render your page invalid. Use a data-* attribute instead:

    <div class="expandListHeaderRow" data-ctryid="your-guid">Foo</div>
    
    var argument = $(this).closest('.expandListContent').prev().find('.expandListHeaderRow').data('ctryid');