28

How $(this.hash) works in jQuery? I presupposed that this script should work like this - if I click to link with href tickets it will show div with id tickets. But it not works.

var search = $("#switcher").find("a"),
    hotels = $("#find").children("div").hide();

search.on('click', function (e) {

  $(this.hash).show()
  e.preventDefault()
});
user2864740
  • 60,010
  • 15
  • 145
  • 220

1 Answers1

56

this.hash reads the href attribute of this, and gets the part of the URL beginning with #. So if the anchor looks like:

<a href="someURL#foobar">

this.hash will be #foobar. When you then use $(this.hash).show(), it's equivalent to doing $("#foobar").show(), so it will show the element with id="foobar".

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 1
    Where is `this.hash` documented? Google gives this page. – Marko Avlijaš Mar 03 '17 at 01:58
  • @MarkoAvlijaš https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/hash – Barmar Mar 03 '17 at 02:09
  • 1
    You shouldn't be searching for `this.hash`, because it depends on what `this` is. You need to look in the documentation of the appropriate HTML element type. In this question, `this` is an `HTMLAnchorElement`. But in many applications, we use `location.hash`. – Barmar Mar 03 '17 at 02:11
  • 1
    Be careful with non-ASCII characters - you may need to use `$(decodeURI(this.hash)).show()`. For example: "#VåraProdukter". – PAB Jul 22 '19 at 15:38