3

i write a code for page transition but the problem is I have a lot of (link to go to in the same page) to exclude, can i do it just one line ?

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

.click(function () {
});

2 Answers2

3

.not accepts a selector, including a selector group. So:

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

Or with :not instead (CSS docs, jQuery docs):

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

(Unlike .not, :not cannot accept a selector group, only a simple selector. But we can chain them within the overall selector.)

That said, you might consider adding a class to the a elements you do or do not want selected for this, and using that class (with or without not depending on which way you go) instead of doing this href check individually.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You can also chain multiple comma-separated attributes inside CSS's :not pseudo-class selector attribute list. Shown below on a list of links with font-weight: bold for demo purposes.

While this runs in at least Chrome and Safari on desktop, I'm not sure whether it's part of the current standard, is forthcoming, or is non-standard. For instance, I couldn't find the behavior documented on MDN, though I did find it mentioned 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>
Taylor D. Edmiston
  • 12,088
  • 6
  • 56
  • 76