$(":not(selector)") in plain/ vanilla javascript?

时间:2016-10-20 12:35:52

标签: javascript jquery ecmascript-6

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?

2 个答案:

答案 0 :(得分:5)

use document.querySelector or document.querySelectorAll :

//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))

答案 1 :(得分:3)

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.