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?
source share