Yusuf Akyol
Yusuf Akyol

Reputation:

How to select links but not child links in jQuery?

How in jQuery can I select just the links inside a div element and not the child div elements contained within that div?

<div>
    <a>Link 1</a>
    <a>Link 2</a>
    <div>
        <a>Not these 1</a>
        <a>Not these 2</a>
    </div>
</div>

Upvotes: 3

Views: 18224

Answers (5)

Lord Loh.
Lord Loh.

Reputation: 2477

I had the same need and looked around. Inspired by a few answers here I wrote this

$('div a').not('div div a')

I have tested this and it works! :-)

Upvotes: 0

Zac Imboden
Zac Imboden

Reputation: 771

I think Danita was on the right track, but her sample did not work for me either. Using .not(), however, did work:

Given:

<div id="testdiv">
    <span><a>span a</a></span> <a>a</a>
    <div>
        <a>div a</a><span><a>div span a</a></span>
    </div>
</div>

find only a tags not nested inside nested divs.

var test = $('#testdiv').find('a').not('#testdiv div a');
$(test).each(function(){
    trace( $(this).html());
});

Not only will it ignore a tags inside the nested div, it will NOT ignore the a tags nested in spans.

Upvotes: 1

redsquare
redsquare

Reputation: 78667

use the direct child selector >

e.g

$('div>a')

UPDATE: to appease Mr RoBorg

If you do have anchors inside nested elements inside the first div then the following will work. This uses a filter to ensure that the parent div is indeed the div you are targetting rather than a nested div.

Demo

  var firstDivAnchors = $('div a').filter( function(){
        return $(this).closest('div').is('#yourDiv');
  });

Upvotes: 12

Ricardo Vega
Ricardo Vega

Reputation: 1975

I don't remember quite well, but doesn't children() does this work?

$(thisDiv).children('a')

In docs.jquery.com it reads: children() Get a set of elements containing all of the unique immediate children of each of the matched set of elements.

Upvotes: 1

Danita
Danita

Reputation: 2514

If there is a specific div you want to target, you can try:

$("div#mydiv a :not(div a)");

EDIT: It would be great if you post some more context (HTML) :)

Upvotes: 6

Related Questions