1

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');
});
  • 2
    tangential: just as an fyi, you should close your `` tags – indubitablee Sep 30 '15 at 15:30
  • possible duplicate of [How to get only direct child elements by jQuery function](http://stackoverflow.com/questions/3687637/how-to-get-only-direct-child-elements-by-jquery-function) – isherwood Sep 30 '15 at 15:39

1 Answers1

6

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>
ps2goat
  • 8,067
  • 1
  • 35
  • 68
  • 2
    You should remove the `.not(...)` method from the chain. – Phylogenesis Sep 30 '15 at 15:32
  • @Phylogenesis, I was just looking at that, too. I'd have to clarify the OP's intent, but it seems like you are correct in his intentions (which is why I used the direct descendant selector). – ps2goat Sep 30 '15 at 15:34
  • Thank you for your answers! Removed the .not() method and used @ps2goat 's code but the links have the default behavior. Using '#main a' changes the attribute of all links to _blank but changing it to '#main > a' does nothing. If it helps, I'm inserting this code into a CMSMS template and using the {cms_jquery} tag to get the source. However this should not be an issue since '#main a' works. – user3394674 Sep 30 '15 at 16:02
  • @user3394674, that seems like a different question since you didn't mention any other technologies. I don't have any experience with `cmsms`, but depending on your environment, you may need to clear the cache on the server. It could be a lot of other things, as well. Rackspace cloud hosting, for example, requires additional work to clear the cache and restart asp.net applications compared to a traditional server setup. – ps2goat Sep 30 '15 at 18:01