user3394674
user3394674

Reputation: 19

Apply attr to div but not to children (JQuery)

I have some html code looking like this:

<div id='main'>
    <a href=''>
    <div id='otherA'>
            <a href=''>
    </div>
    <div id='otherB'>
            <a href=''>
    </div>
</div>

I would like to apply the attribute "target" to elements of #main but not of #other using JQuery. I tried a few things and I think this is the closest I got but it does not seem to work.

$(document).ready(function(){
    $('#main a').not(['#otherA a', '#otherB a']).attr('target', '_blank');
});

Upvotes: 1

Views: 65

Answers (1)

ps2goat
ps2goat

Reputation: 8475

use #main > a as your selector. That will only pick 'a' tags immediately under #main.

$(document).ready(function(){
    $('#main > a').attr('target', '_blank');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id='main'>
    <a href=''>main a</a>
    <div id='otherA'>
            <a href=''>asdsf</a>
    </div>
    <div id='otherB'>
            <a href=''>kjklsdf</a>
    </div>
</div>

Upvotes: 6

Related Questions