gkolan
gkolan

Reputation: 1581

jQuery: Get all links from HTML page except if the link falls under certain class or id

<nav>
  <ul>
    <li><a href="#">Link1</a>
    </li>
    <li><a href="#">Link2</a>
    </li>
    <li><a href="#">Link2</a>
    </li>
  </ul>
</nav>
<div>
  <a href="#">Link4</a>
</div>
<div>
  <p>
    <a href="#">Link5</a>
  </p>
</div>
<p>
  <a href="#">Link6</a>
</p>
<div class="stackoverflow">
  <a href="#">Link7</a>
  <a href="#">Link8</a>
  <a href="#">Link9</a>
</div>
<p class="stackoverflow">
  <a href="#">Link10</a>
</p>
<p>
  <a href="#">Link10</a>
</p>

What is the best way to ignore all the links under class stackoverflow and select all the rest of anchor tags in the dom?

Is selecting every anchor tag $('a') and then grabbing $('.stackoverflow a') anchor tags and then removing the common elements the best way to do this?

Upvotes: 2

Views: 191

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You can also use filter function :

$('a').filter(function(){
    return !$(this).parent().hasClass('stackoverflow');
});

Hope this helps.


$('a').filter(function(){
    return !$(this).parent().hasClass('stackoverflow');
}).css('background-color', 'yellow');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#">Link1</a>
    <li>
      <li><a href="#">Link2</a>
        <li>
          <li><a href="#">Link2</a>
            <li>
</ul>
<div>
  <a href="#">Link4</a>
</div>
<div>
  <p>
    <a href="#">Link5</a>
  </p>
</div>
<p>
  <a href="#">Link6</a>
</p>
<div class="stackoverflow">
  <a href="#">Link7</a>
  <a href="#">Link8</a>
  <a href="#">Link9</a>
</div>
<p class="stackoverflow">
  <a href="#">Link10</a>
</p>
<p>
  <a href="#">Link10</a>
</p>

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 240928

You could use the :not() pseudo class like this:

Working Example

$('a:not(.stackoverflow a)');

This will negate all a elements that are descendants of a .stackoverflow element.

Alternatively, the .not() method would work as well:

$('a').not('.stackoverflow a');

Upvotes: 3

Related Questions