What’s $(this.hash) in jQuery for?

Asked

Viewed 500 times

1

In the code below I came across the syntax $(this.hash):

$('a').on('click', function(e) {
  e.preventDefault();

  $(this.hash).show();
});

I got a little confused thinking it might be something related to encryption, but it’s not.

What is the purpose of $(this.hash)?

3 answers

8


This is not a jQuery syntax exactly, to understand we need to first talk about the this.hash, elements such as <a> and <link> (and possibly some others, which support Urls), are represented by certain interfaces on objects in the Javascript engine of each browser

Of course it is possible to represent HTML elements from a string on the server side with a parse HTML, as the native API itself DOMParser

Taking as an example <a> and <link>, are represented by:

  • HTMLAnchorElement for <a>
  • HTMLLinkElement for <link>

So when you catch something like this:

var foo = document.querySelector('a');

The anchorage/link found (if it does not exist returns null), will be an object HTMLAnchorElement

As you can see in https://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement, it supports several properties to read the URL defined in the HTML element, some examples

HTMLAnchorElement.hash
HTMLAnchorElement.host
HTMLAnchorElement.hostname
HTMLAnchorElement.password
HTMLAnchorElement.pathname
HTMLAnchorElement.port
HTMLAnchorElement.protocol

That is, it is treated as an object to be able to manipulate without you having to use a getAttribute() and parse in the URL hand, you could simply change the host of destination or the hash target setting values, example:

var meulink = document.querySelector('#meulink');

//Troca stackoverflow.com por pt.stackoverflow.com
meulink.host = 'pt.stackoverflow.com';

//Atualiza a hash com o horario atual
setInterval(function () {
    var d = new Date;
    meulink.hash = 'hora_' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
}, 1000);
<a target="_blank" id="meulink" href="https://stackoverflow.com.br/search?q=VanillaJS">Olá mundo!</a>

Now if I were to use setAttribute or .href =, would be much more complicated, would have to parse manually the returned string trying to identify what the host and what is the hash and substitutes.

I understand that the answer seems long so far, but it is because I really believe it is pertinent to understand how certain elements work on Javascript objects, returning to their code, the this alone returns the element clicked, in case the anchor <a> that trigger the event:

$('a').on('click', function(e) {
  e.preventDefault();

  $(this.hash).show();
});

Then is caught the this.hash, which is as I mentioned before, will return the URL HASH, so if the HASH exists it will return its value with the prefix #, in CSS selectors, document.querySelector and document.querySelectorAll (and jQuery) the # also represents ID, which is pertinent to the case, so your code will search for the element with the specific ID and will execute the function .show() of library jQuery to force display element chance it is hidden by display:none, for example, if the hash returns something like #foobar it will look for any element (can be DIV or not) like this:

 <div id="foobar"></div>

And if it’s hidden, it’ll be forced to show.


About the URL interface

Note that each browser implements its own interface that is accessible to Javascript (and each browser has its own javascript engine too, in addition to the DOM/CSS/SVG itself), browsers like Chrome and Firefox implement in the interfaces of HTMLAnchorElement and HTMLLinkElement (and others):

Then the URL (or HTMLHyperlinkElementUtils) would be a good way to manipulate strings that contain a URL, and this could even generate value for links, forms that will be created in the future in dynamic pages, which technically a document.createElement('a') could also do (if you want some support for older browsers), of course in this last case maybe don’t have everything, as an example URL.searchParams, that facilitates picking up values of a querystring (?foo=bar&baz=boo)

I know the answer seems "long", but the intention is to explain technically how things work, since this is not even a jQuery syntax, as the question’s title states, but rather a native feature of the DOM and API URL Javascript combined with jQuery (which is a "third party" lib and you could make the same use of HTMLAnchorElement.hash without jQuery)

2

It reads the attribute passed by the URL after "#" as reference to the id defined.

Something like this:

<a href="seuURL#barra">

$(this.hash) will be #bar. When you use $(this.hash).show(), is equivalent to making $("#barra").show(), then displays the element with id = "barra".

  • 1

    You just summed up the other answer but in the end you didn’t explain why

  • What would be the point of getting a reference in a url? defined briefly for reasons of just testing this command it already works, thus seeing practically in real time!

-1

Be for example the HTML code below:

<a href="//exemplo.com#teste">

The $(this.hash) will read the property href of the element <a>, returning the # together with the text that follows it, resulting in #teste.

In other words, execute:

$(this.hash).show();

It’s the same as doing:

$('#teste').show();
  • 2

    You just summed up the other answer but in the end you didn’t explain why

Browser other questions tagged

You are not signed in. Login or sign up in order to post.