I have a lot of .not () (exclude) how can I do this with just one line

I am writing code to navigate a page, but the problem is that I have many (link to go to the same page) to rule out, can I only do this one line?

$('a')
.not('[href="#"]')
.not('[href="#navShow"]')  // the problem
.not('[href="#navHide"]')  // the problem
.not('[href="#about"]')  // the problem

.click(function () {
});

      

+3


source to share


2 answers


.not

accepts a selector, including a selector group. So:

$('a').not('[href="#"], [href="#navShow"], [href="#navHide"], [href="#about"]').click(function () {
});

      

Or instead of :not

( CSS docs , jQuery docs ):



$('a:not([href="#"]):not([href="#navShow"]):not([href="#navHide"]):not([href="#about"])').click(function () {
});

      

(In contrast .not

, :not

cannot accept a selector group, only a simple selector, but we can chain them within a common selector.)

That being said , you might consider adding a class to the elements a

you do or don't want to be selected for that, and using that class (with or without not

depending on which way you go) href

check individually instead .

+3


source


You can also bind multiple comma separated attributes in the attribute list of the CSS alias selector :not

. Below is a list of font-weight links: bold for demonstration purposes.

While this works, at least in Chrome and Safari on the desktop, I'm not sure if it is part of the current standard, expected, or non-standard. For example, I could not find the behavior recorded on MDN, although I did find it in a comment on SO .



$('a:not([href="#b"], [href="#c"], [href="#e"])').each(function(idx, val) {
  $(val).css('font-weight', 'bold');
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#a">link a</a></li>
  <li><a href="#b">link b</a></li>
  <li><a href="#c">link c</a></li>
  <li><a href="#d">link d</a></li>
  <li><a href="#e">link e</a></li>
  <li><a href="#f">link f</a></li>
</ul>
      

Run codeHide result


0


source







All Articles