this.href vs $(this).attr(‘href’)

The href property in plain Javascript will have the semantic attached to it. It returns the destination URL which the link will lead to. It doesn’t matter how it was written (absolute or relative URLs).

When you use the $(this).attr("href") you are retrieving directly the value of href attribute just like any other attribute, so it will return the exact value rendered in the HTML.

For your case then, it’s better to use $(this).attr("href")

If you don’t want to use jQuery, there’s yet another solution, using just plain JavaScript:

this.getAttribute('href')

Leave a Comment