What does the extra "$ ()" in the $ ($ ()) selector do?

I want to implement jQuery scrolling for one of the projects I'm working on.

I found this jsfiddle ( https://jsfiddle.net/mekwall/up4nu/ ) that I managed to implement in my project. I want to change it, but I'm trying to understand what this bit of code means.

var topMenu = $("#top-menu"), menuItems = topMenu.find("a"), // Anchors corresponding to menu items scrollItems = menuItems.map(function(){ var item = $($(this).attr("href")); if (item.length) { return item; } }); 

I know that in the general case, the code will look for all the "a" links, find href through the attr () function, and if it exists, add it to the map. That I do not understand

  $($(this).attr("href")); 

What does the optional $ () selector mean? I understand that

 $(this).attr("href"); 

means selecting / retrieving href for this item. What does $ () do? Is it a nested selector? I tried a search on Google, but I could not find the answers to it, or my google-fu does not match the face value.

Besides,

 $($(this).attr("href")); 

extract links only in the following index.html format # section-one or # section-one?

Update

Also, how would ".length" determine if an element exists in the DOM? When I checked the console logs, the href link with "index.html # section-one" will return length 0, and one with "# section-one" will return length 1. Why is this happening?

+5
source share
3 answers

In your case, href are binding names (or fragment identifiers), which are usually doubled as an id selector. By matching the href attribute and then wrapping it with $() , you effectively select the element with that id .

So, <a href='#faq'> usually goes to the named anchor "faq", but wrapping the value of attr href , you select $('#faq') .

+2
source

This code assumes that the href attribute will be an id reference, such as #about . Outer $() moves forward and grabs this #about element for you.

+3
source
 $($(this).attr("href")); 

The above expression $(this).attr("href") will specify the href attribute of the specified html element, which is a string. If you want to convert this string to a jQuery object and do further manipulations, you can achieve this using extra $ () like

 $($(this).attr("href")) 
+1
source

All Articles