views:

1748

answers:

3

What does selector 'a[href*=#]' mean in jQuery? And what does location.pathname, location.host, this.hash, target.size() mean?

The complete code snippet is:

$(document).ready(function() {
  $('a[href*="#"]').click(function() {
     if (location.pathname == this.pathname && location.host == this.host) {
       var target = $(this.hash);
       target = target.size() && target || $("[name=" + this.hash.slice(1) +']');
       if (target.size()) {
           target.ScrollTo(400);
           return false;
       }
    };
  });
});
+1  A: 

The a[href*="#"] selector means in jQuery the same as in CSS: It matches any A element that’s href attribute value contains a #.

Gumbo
+7  A: 

First off the selector 'a[href*="#"]' means any link that has a # in the href attribute. For example, it would match the following elements:

<a href='#someSection'>Blah</a>
<a href='#otherSection'>Foo</a>
<a href='foobar.html#otherSection'>Foo</a>

See Selectors/attributeContains from the jQuery documentation.

As for location.host and location.pathname, they refer to the host and the path in the current url.

For example, if the page was located at http://www.example.com/somepage.html, then:

  • location.host would be www.example.com
  • location.pathname would be /somepage.html

As for this.hash, that is a property on the link that was clicked, which will evaluate to the 'hash' portion of the link. For example:

<a href="somepage.html#someSection">Foobar</a>

For the element above, this.hash would be #someSection.

Lastly, as for .size(), in the case above, that is checking the number of elements that were selected in the jQuery object.

The author of the code you posted is attempting to do something cute: he's expecting that his page will have an element present that has an id matching the hash of the link that was clicked.

For example, if this.hash is #someSection, the author checks if there is an element with id equal to 'someSection'"

var target = $('#someSection');
// if target.size() is 0, that means there was no such element with id = 'someSection'
TM
A: 

It selects all anchors, which refer to elements inside a page (contains #), e.g. elements like

<a href="index.html#top"> ... </a>

Look at the [selector API][1] to understand it:

  1. a selects anchors
  2. [attr*=val] selects elements which have attr attributes and the attribute's value contains val

Regarding your other questions:

location.host is the host the current page was retrieved from, location.pathname is the pathname of current page. The code basically checks if the clicked link refers to an element within the current page.

this.hash in the context of the link returns the element id the link refers to (the text after the '#'). So $(this.hash) selects the element that the link refers to.

target is the result of above selection, so it is in fact a list of elements. target.size() checks how many elements were found (zero or one).

Zed