Search code examples
javascriptjquerytraversaldom-traversal

go back(traverse up) from "this" and find specific element with jQuery


Even with jQuery traversing from a specific point is sometimes a riddle to me.

My HTML Structure looks like this:

<div class="grid__area grid__area--empty">
    <div id="streamcontainer" class="streamcontainer">
         <div class="inputer">
            <form action="">
               <input type="text" name="purl" value="XXX" id="" class="">
               <input type="submit" value="Submit" id="submit" class="submiturl"> //starting "this" point
            </form>
         </div>
         <div id="player" class="player"></div> // The Endpoint
    </div>
</div>

The starting point is the clicked #submit.

The Endpoint should be #player.

What have I tried so far in many different variations:

$(this).find('.player').attr('id');
$(this).parent('.streamcontainer').find('.player').attr('id');
$(this).parent('.streamcontainer').closest('.player').attr('id');

Thanks for any help!


Solution

  • I think the OP was accidentally using .parent() instead of .parents()

    .parent():  traverses to the immediate parent of 
    
    .parents(): allows us to search through the ancestors of these elements in the DOM tree
    

    So I think what the OP was after originally was:

    $(this).parents('.streamcontainer').find('.player').attr('id');
    

    Unless this is an exercise in DOM traversal I'm not sure why you'd want to do this? :)