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?
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.
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.
In jQuery, you can use the . prop() method to get the href value of an anchor tag.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With