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.


Need Your Help

XSLT 2.0: filter on match

xslt-2.0

&lt;xsl:template match="lat:entry[document(lat:file)//h2]"/&gt;

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.