SystemicPlural
SystemicPlural

Reputation: 5789

How do I select these nested tags with jQuery

How do I find theses two examples using the same code.

<div>
  <div>
    <span class='example-1'></span>
  </div>
  <ul class='find-me'> <!-- find this for example 1 -->

    <li>
      <span></span>
      <ul class='find-me'></ul>
    </li>

    <!-- Any number of li tags here -->

    <li>
      <span class='example-2'></span>
      <ul class='find-me'></ul>  <!-- find this for example 2 -->
    </li>

    <!-- Any number of li tags here -->

  </ul>
</div>

Given that I have the jQuery object for for example-1 and example-2, how do I write an identical selector for both examples? Is it possible?

I can't just do selector.parent().find(".find-me") because this won't work for the first example. I can't do selector.parent().parent().find(".find-me:first") because this will select the wrong find-me in the second example.

I need to somehow say go up to the grandparent then go to where you started and find the next find-me class.

Edit: The answers so far all seem to be misunderstanding. There must be only one selector that works for both examples, and the selector must be relative to the jQuery object that represents the example span.

Upvotes: 0

Views: 541

Answers (4)

Blender
Blender

Reputation: 298582

Here's the best that I can come up with:

var $example1 = $(".example-1");
var $example2 = $(".example-2");

$example1.add($example1.parents()).siblings('.find-me').css("color", "red");
$example2.add($example2.parents()).siblings('.find-me').css("color", "blue");​

Demo: http://jsfiddle.net/HNfpM/3/

Upvotes: 2

Cihad Turhan
Cihad Turhan

Reputation: 2859

How about $("div span, li span") or you can use css3 selector:[att^=val] http://www.w3.org/TR/css3-selectors/ I would use css3 selector actually. I've added a working demo on the comment

Upvotes: 0

levi
levi

Reputation: 3521

$('div > ul.find-me'); <!-- find this for example 1 -->



$('div > ul > li > ul.find-me'); <!-- find this for example 2 -->

Upvotes: 0

Anton
Anton

Reputation: 32591

$('.find-me')[0] for first example $('.find-me')[2] for second example

Upvotes: 0

Related Questions