Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.href vs $(this).attr('href')

After reading this article net.tutsplus.com/tutorials/javascript-ajax/14-helpful-jquery-tricks-notes-and-best-practices/ I came to conclusion that using this.href is more efficient.

However, when I tried to use it on one of my projects, I saw that this.href returns not only href but also appends a url of a website. For example <a href="tab-04"></a>this.href will return http://example.com/abc/tab-04 and $(this).attr('href') will return only tab-04.

You can see an example here http://jsfiddle.net/UC2xA/1/.

$(this).attr('href') however returns exactly what I need and nothing more.

My question is this, how can I rewrite (or do what is necessary) this.href so that it would only return tab-04?

EDIT

Doug you are right on the money with

this.getAttribute('href')
like image 944
user Avatar asked Aug 08 '11 01:08

user


People also ask

What is attr href?

Definition and Usage The href attribute specifies the URL of the page the link goes to. If the href attribute is not present, the <a> tag will not be a hyperlink.

How to replace anchor tag href in jQuery?

Answer: Use the jQuery . attr() Method You can use the jQuery . attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.

What is location href in js?

The location. href property sets or returns the entire URL of the current page.

How do I change the location of a Windows href?

href = "https://www.example.com"; // Assigns a new URL to the current window. window. location. assign("https://www.example.com"); // Replaces the location of the current window with the new one.


1 Answers

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') 
like image 148
Doug Avatar answered Oct 04 '22 00:10

Doug