Edward Gargan
Edward Gargan

Reputation: 153

Which elements does the jQuery expression $('a[href*=#]:not([href=#])') target?

I'm new to jQuery, and have found a code snippet that will scroll to a certain part of a page pointed to by local, or 'anchor' links.

$('a[href*=#]:not([href=#])').click(function() {

        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {

        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 500);
          return false;
        }

      }
 });

I understand that it must select links with local hrefs, but was wondering exactly what the difference is between the two 'clauses' of the selector.

Upvotes: 1

Views: 491

Answers (4)

Obsidian Age
Obsidian Age

Reputation: 42304

The asterisk (*) character after the attributes in jQuery denotes the attribute contains selector.

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

Breaking this down:

  • a: Target all the <a> tags
  • [href*=#]: Target all the href attributes that contain #.
  • :not([href=#]): Do not target href attributes that have an href value of exactly #.

So, in short, the selector targets any <a> tags that contain a # in their href attribute where # is not the only part of the href attribute.

Considering URIs use hashes to denote IDs on the page, this allows the jQuery to scroll to an element on the page, rather than simply 'jump' to it.

Hope this helps!

Upvotes: 1

cusmar
cusmar

Reputation: 1913

a[href*=#] gets all links that contains #, but :not([href=#]) excludes links with exactly # in their href attribute.

This link will be selected:

<a href="http://www.example.com/here#top" title="">Link</a> 

But this one not:

<a href="#" title="">Link</a> 

Upvotes: 3

leepowers
leepowers

Reputation: 38318

The first rule will match any URL with a hash component, e.g. <a href="#jump-to-id">

The second not rule filters out any URLs that are just an empty hash, e.g., <a href="#">

Upvotes: 3

Lars Gyrup Brink Nielsen
Lars Gyrup Brink Nielsen

Reputation: 4095

It matches anchors with an href attribute that includes # but is not only #.

Upvotes: 3

Related Questions