jQuery - multiple :not selector

JqueryJquery Selectors

Jquery Problem Overview


I'm trying to target page-wide links that do not start with a '#' and do not include in-line javascript but I'm having problems figuring out how to structure the selector properly.

Based on what I've googled about multiple selectors this should work, both selectors work independently, just not together!

$('a:not([href*=javascript]), a:not([href^=#])')
.each(function(){...

Jquery Solutions


Solution 1 - Jquery

Try using

$('a:not([href*=javascript]):not([href^=#])') ...

Solution 2 - Jquery

You could also try:

$('a').not('[href^=#],[href*=javascript]')

Solution 3 - Jquery

As indicated in https://stackoverflow.com/questions/6166871/jquery-multiple-selectors-in-a-not , this is the correct way to do this:

$( 'a:not([href*=javascript],[href^=#])' )

Don't forget to put quotes around commas if you already already have your selectors to negate in variables

var selOne = '[href*=javascript]';
var selTwo = '[href^=#]';
$('a:not(' + selOne + ',' + selTwo + ')')

I admit that the code gets a bit confusing but it has an advantage, you can do things such as this:

var selOne = '[href*=javascript], [href^=#]';
var selTwo = '.anotherSelector, .andAnother, .andSoOn';
$('a:not(' + selOne + ',' + selTwo + ')')

It's useful whenever you need to group selectors for some reason, ie. using the same group of selectors somewhere else in the code.


A live example using the same technic

$('div:not(.rose-flower,.bus-vehicle)').css('color','red');

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="bus-vehicle">I am a bus</div>
<div class="strawberry-fruit">I am a strawberry</div>
<div class="rose-flower">I am a rose</div>

Also on http://jsfiddle.net/bmL8gz5j/


:not vs .not(): For performance reasons, you should use :not rather than .not(), see https://stackoverflow.com/questions/8845811/performance-differences-between-using-not-and-not-selectors

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHill79View Question on Stackoverflow
Solution 1 - JqueryjtbandesView Answer on Stackoverflow
Solution 2 - JqueryDarkAjaxView Answer on Stackoverflow
Solution 3 - JqueryAdrien BeView Answer on Stackoverflow