Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does $($(this).attr('href')) mean in jQuery?

I am fairly new to jQuery and understand the basics, but I am having issues targeting certain pieces of the page so I need to fill in some gaps in knowledge.

I do understand $(this).attr('href') would get the attribute of href within the currently focused/clicked element.

But what if it’s written like this $($(this).attr('href'));?

It’s code I have in a script I didn’t write, and I’m not sure if that’s just an error or intentional.

I have a feeling this is pretty basic but how to search for $($())? And when I search for $($(this).attr('href')) all I get is documentation on the original clause which I already understand.

Is it just a typo or a separate use case?

like image 559
weekapaug Avatar asked Apr 07 '18 14:04

weekapaug


People also ask

What is ATTR jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

How to set href link with 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.

How to get href value of anchor tag in jQuery?

In jQuery, you can use the . prop() method to get the href value of an anchor tag.


1 Answers

As you said, $(this).attr('href') returns the matched element's href. That's a string. The string is then passed to $, which doesn't know it's a href so treats it as it does any other string: it parses it, decides if it looks like HTML or a selector, then returns the resulting jQuery instance.

Presumably, this is in some context where the href happens to also be either a valid selector or valid HTML. As was mentioned in comments, a likely candidate is a string like #something, which as a href links to the scroll position of the element with ID something, and as a selector tells jQuery to select the same element.

like image 84
twhb Avatar answered Sep 29 '22 05:09

twhb