3

How can I write $(":not(selector)") in plain javascript?

jQuery:

var links = $('a:not(.not-lightbox-item a)', this);

HTML:

<div id="links">
    <div class="not-lightbox-item">
        <a href="projects.html" class="button-back">
            <span class="glyphicon glyphicon-hand-left glyphicon-circle-arrow-leftx" title="Back"></span>
        </a>

        <h2 class="heading item-heading">(Title) Ways of Something</h2>

        <p>Lorem ipsum dolor sit amet <a href="#">Excepteur sint occaecat</a> cupidatat non proident</p>
    </div>

    <a href="images/banana.jpg" title="Banana">
        <img src="images/thumbnails/banana.jpg" alt="Banana">
    </a>
    <a href="images/apple.jpg" title="Apple">
        <img src="images/thumbnails/apple.jpg" alt="Apple">
    </a>
    <a href="images/orange.jpg" title="Orange">
        <img src="images/thumbnails/orange.jpg" alt="Orange">
    </a>
</div>

Any ideas?

Run
  • 54,938
  • 169
  • 450
  • 748

2 Answers2

16

use document.querySelector or document.querySelectorAll as the solution :

//returns first element matching
document.querySelector("a:not(.not-lightbox-item a)");

//returns all elements matching
document.querySelectorAll("a:not(.not-lightbox-item a)");

However @George Katsanos is right, it is clearer (and probably faster) to use a class like .lightbox-item than a double negation like a:not(.not-lightbox-item a)

Shreyash Shetty
  • 103
  • 1
  • 5
n00dl3
  • 21,213
  • 7
  • 66
  • 76
0

Why not toggle a class which has the selector applied to it in in pure CSS?

.className {
  color: blue;
}

var myitem = document.querySelector('.item')
myitem.classList.toggle('className');

I would resort to :not only if I had no control over the HTML.

George Katsanos
  • 13,524
  • 16
  • 62
  • 98
  • thanks. i think I'll go for `links = this.getElementsByClassName('lightbox-item');` instead. – Run Oct 20 '16 at 12:54