Arthur
Arthur

Reputation: 221

jQuery Find all href but not in

I have the following HTML document

I want all the href, but not the href inside "main"

Only "main" may be used for this in the jQuery

$('a').each(function() {
  console.log($(this).attr('href'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
  <a href="url1">link text 1</a>
</header>

<main>
  <a href="url2">link text 2</a>
</main>

<footer>
  <a href="url3">link text 3</a>
</footer>

Upvotes: 0

Views: 56

Answers (2)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

If you want to stick with jQuery, you can use jQuery's built-in not() function.

$('a').not('main > a').each(function() {
  console.log($(this).attr('href'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
  <a href="url1">link text 1</a>
</header>
<main>
  <a href="url2">link text 2</a>
</main>
<footer>
  <a href="url3">link text 3</a>
</footer>

If you want a pure HTML5 solution, you can use the native CSS 3/4 :not() selector.

document.querySelectorAll('body *:not(main) > a').forEach(el =>
  console.log(el.getAttribute('href')));
<header>
  <a href="url1">link text 1</a>
</header>
<main>
  <a href="url2">link text 2</a>
</main>
<footer>
  <a href="url3">link text 3</a>
</footer>

Upvotes: 0

j08691
j08691

Reputation: 207861

Just use .not() like:

$('a').not('main > a').each(function() {
    console.log($(this).attr('href'));
});

Example

$('a').not('main > a').each(function() {
  console.log($(this).attr('href'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<header>
  <a href="url1">link text 1</a>
</header>

<main>
  <a href="url2">link text 2</a>
</main>

<footer>
  <a href="url3">link text 3</a>
</footer>

Upvotes: 1

Related Questions