Lord A.
Lord A.

Reputation: 23

Target all links except those in DIVs using jQuery

I want to target all links in .entry-content, except those in DIVs in it. So I have this:

$(document).ready(function($) {

  // Target all links in entry-content except those in DIVs
  $('.entry-content a')
    .not($('div a'))
    .not('[href*="' + window.location.host + '"]')
    .attr('rel', 'nofollow noopener noreferrer')
    .attr('target', '_blank');

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="entry-content">
  <div><a href="#">Exclude this</a></div>
  <p><a href="#">Include only this</a></p>
  <a href="#">Or any other link as long as it's not in DIV</a>
</div>

This part doesn't work: .not($( 'div a' ))

Any help would be appreciated. Thanks!

Upvotes: 1

Views: 43

Answers (1)

thingEvery
thingEvery

Reputation: 3434

Use > to target direct descendants.

.not('.entry-content>div>a')

Example:

$(document).ready(function($) {

 // Target all links in entry-content except those in DIVs
 $('.entry-content a')
   .not('.entry-content>div>a')
   .not('[href*="' + window.location.host + '"]')
   .attr('rel', 'nofollow noopener noreferrer')
   .attr('target', '_blank')
   .css('color', 'red');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="entry-content">
 <div><a href="#">Exclude this</a></div>
 <p><a href="#">Include only this</a></p>
 <a href="#">Or any other link as long as it's not in DIV</a>
</div>

Upvotes: 2

Related Questions