Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery selecting certain 'level' of elements?

Say I have the following markup:

<div>
    <h3><a href="">link I want to select</a></h3>
        <div>
             <h3><a href="">link</a></h3>
        </div>
    <h3><a href="">link I want to select</a></h3>
    <h3><a href="">link I want to select</a></h3>
    <a href="">link</a>
</div>

Assuming the following...

  • The elements I want to find are all at the same level of nesting
  • I may not know what the specific nesting elements are (so can't use a specific selector)

...is there a clever way to select 'first anchor tag, and all other anchor tags that are nested at that same level' so that it returns the 1st, 3rd, and 4th links?

Worse case, we need to go in and just add specific classes to our HTML, but it'd be great if this could be done via pure selectors.

like image 846
DA. Avatar asked Feb 18 '10 19:02

DA.


2 Answers

Not a pure selector, but how about:

var depth = $('#myanchor').parents().length;
var all_at_depth = $("a").filter( function() { $(this).parents().length == depth; } );

You can use parentsUntil() to get the distance between #myanchor and a specific parent, if that helps.

like image 189
jlew Avatar answered Nov 11 '22 22:11

jlew


Check out siblings() and :first.

like image 35
Francisco Aquino Avatar answered Nov 11 '22 21:11

Francisco Aquino