Limiting scope of JQuery selection with nested, repeating element structure

Given a repeating, nested element structure, for example:

<div class="A">

  <span class="B></span>
  <span class="B></span>

  <span class="B">
     <div class="A">
        <span class="B"></span>
     </div class="A">
  </span>

</div>

How can I select the last <span class="B"></span> that is a direct child of the root <div class="A"></div> element?

I tired:

div.A > class.B

...but (correctly) this also matches the last element which is not a direct child of the root <div class="A"></div> element.

Answers


you could either add some id, classes, or a data-level object in order to make the nesting search easier, or you could do this slightly hackish version:

$('div.A').first().children('span.B').last();

I would suggesting adding a data-level, id, or other class to handle the level though.

For example, change your HTML to:

<div class="A" data-level="first">

  <span class="B" data-level="second"></span>
  <span class="B" data-level="second"></span>

  <span class="B" data-level="second">
     <div class="A" data-level="third">
        <span class="B" data-level="fourth"></span>
     </div>
  </span>

</div>

and you can do things like:

$('span.B[data-level="second"]').last();

etc.


jQuery has the :last selector. It's still not entirely clear to me which object you're trying to select.

If you want the last <span class="B"></span> that is a direct child of the root <div class="A">, then you have these options:

1) Give the root an identifying class:

<div class="A root">

  <span class="B></span>
  <span class="B></span>

  <span class="B">
     <div class="A">
        <span class="B"></span>
     </div>
  </span>

</div>

And this selector:

A.root > .B:last

2) Specify the parent of the root object to identify it:

body > .A > .B:last

3) Use some code to identify the root object:

$(".A").filter(function() {
    // filter out items that have an "A" class as a parent
    return($(this).parents(".A").length == 0);  
}).children(".B:last");

Need Your Help

Is MIME type detection the best way to detect a kind of file?

php mp3 mime-types

I’m working on an upload form in PHP that must allow only MP3 files.

How do I test a website design on a mobile device?

mobile responsive-design windows-mobile handhelddevice

I have designed my site with a 900 x 600 fixed background image. On the computer it looks fine. How will it look on a PDA device? Will I have to design it separately for PDA?