0

Within JQuery I am trying to perform the following

  1. Find every link on the page
  2. Where the HREF property starts with '#'
  3. And the ID value is not 'mobileMenu'

This works perfectly:

$("a[href^='#']").each(function () { // links where HREF starts with #
    if ($(this).attr('id') != 'mobileMenu') { // id not equal to mobileMenu
        $(this).click(function () {
            // logic
        })
    }
});

But when I try to combine it into a more succinct search, it fails (the mobileMenu link is still pulled into the array):

$("a[href^='#'], a[id!='mobileMenu']").each(function () {

}

What I am doing wrong please?

EvilDr
  • 8,943
  • 14
  • 73
  • 133

2 Answers2

2

You should not use multiple selector because you want to have an AND condition

$('a[href^="#"]:not(#mobileMenu)').each(...)
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • +1. `:not` is more efficient than `.not()` http://jsperf.com/jquery-css3-not-vs-not – Terry Oct 14 '14 at 08:32
  • @Terry, document says 'it's better to use .not() over $('x:not(y)')' – Bhushan Kawadkar Oct 14 '14 at 08:34
  • CSS3 selectors are generally faster. [Check this link](http://jsperf.com/jquery-css3-not-vs-not), test it in your browser. You have your answer. jQuery doc recommends `.not()` simply because it [makes the code more readable](http://stackoverflow.com/a/8845863/395910) instead of compounding pseudo-selectors together. – Terry Oct 14 '14 at 08:34
  • @Terry it will depend on what is passed to `not()` - http://jsperf.com/jquery-css3-not-vs-not-2 - here an non css3 `:not()` supported selector is passed to the `not()` in such cases `.not()` is better than `:not()` – Arun P Johny Oct 14 '14 at 08:37
  • @ArunPJohny Well `*` is in general an awfully expensive selector :P – Terry Oct 14 '14 at 08:37
  • @Terry yes it is... but then the same load is applied to both the variants... so if a [css3 :not](https://developer.mozilla.org/en-US/docs/Web/CSS/:not) supported selector is there then use `:not()` else `.not()`... – Arun P Johny Oct 14 '14 at 08:39
  • You guys are truly awesome. A perfect answer in under three minutes. I love this site. – EvilDr Oct 14 '14 at 08:44
1

Try this : use .not() to exclude elements from the selected list of elements.

$("a[href^='#']").not('#mobileMenu').each(function () {

}
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57