leon.nk
leon.nk

Reputation: 437

Selecting parents and first child elements with jQuery

I want to select all of an elements parents and their first child, and also the original element itself. Here's an example of the markup:

<ul id="end-here">
  <li>
    <a href="/path">Link</a>
  </li>
  <li class="select-me">
    <a class="select-me" href="/path">Another link</a>
    <ul>
      <li>
        <a href="/path">Submenu link</a>
      </li>
      <li class="select-me">
        <a class="select-me" id="start-here" class="change-me" href="/path">Another submenu link</a>
      </li>
    </ul>
  </li>
</ul>

So starting from $('#start-here') I want all the $('.select-me') stopping at $('#end-here')

I've got this so far

$('#start-here').add($('#start-here').parentsUntil('#end-here', 'li, a'))

However this misses out the a tag child, as they are not direct parents of the original element. So the following element above isn't included:

<a class="select-me" href="/path">Another link</a>

Upvotes: 0

Views: 979

Answers (2)

mekwall
mekwall

Reputation: 28974

Your example code doesn't match up with what you are asking for, "select all of an elements parents and their first child, and also the original element itself". This is how the example code should look:

<ul id="end-here">
  <li class="select-me">
    <a href="/path">Link</a>
  </li>
  <li>
    <a class="select-me" href="/path">Another link</a>
    <ul>
      <li class="select-me">
        <a href="/path">Submenu link</a>
      </li>
      <li>
        <a class="select-me" id="start-here" class="change-me" href="/path">Another submenu link</a>
      </li>
    </ul>
  </li>
</ul>​

And the jQuery selector:

$("#start-here").parentsUntil("#end-here").andSelf().map(function(){
    return $(this).parent().children()[0];
});

The above returns the four elements that in the example have the select-me class.

However, if your example code is correct, the selection process cannot be as generic or flexible and you will have to specify some element types:

var elems = $("#start-here").parentsUntil("#end-here", "li");
elems.add(elems.children("a"));

Thanks to Stano for the above solution.

Upvotes: 3

Barmar
Barmar

Reputation: 781058

Untested, but I think it should be something like:

$('#start-here').add($('#start-here').andSelf().parentsUntil('#end-here', 'li, a')).andSelf().children().first();

Upvotes: 0

Related Questions