\$\begingroup\$
\$\endgroup\$
1
The current code I have runs fine, but I'm curious about some other approaches to making this more DRY.
var topLinks = document.querySelectorAll('.navUtility-listItem a');
for(var i=0; i<topLinks.length; i++){
if((topLinks[i].getAttribute('href').indexOf('a') > -1)){
topLinks[i].className += ' top-nav-a';
} else if (topLinks[i].getAttribute('href').indexOf('b') > -1){
topLinks[i].className += ' top-nav-b';
}
}
var bottomLinks = document.querySelectorAll('.footerMain-listPlatformItem a');
for(var i=0; i<bottomLinks.length; i++){
if((bottomLinks[i].getAttribute('href').indexOf('a') > -1)){
bottomLinks[i].className += ' bottom-nav-a';
} else if (bottomLinks[i].getAttribute('href').indexOf('b') > -1){
bottomLinks[i].className += ' bottom-nav-b';
}
}
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Aug 17, 2016 at 17:00
Rob ChanRob Chan
-
\$\begingroup\$ Can you add corresponding HTML code too \$\endgroup\$Tushar– Tushar2016年08月19日 12:00:38 +00:00Commented Aug 19, 2016 at 12:00
1 Answer 1
\$\begingroup\$
\$\endgroup\$
0
You can have a function to which you will pass your links as an object (will be passed by reference) and classes. In the function, if you will pass the top or bottom links, they will be passed by reference and every change in the function will affect the original object.
function setClasses(links, classes){
for(var i = 0; i < links.length; i++){
if( (links[i].getAttribute('href').indexOf('a') > -1) ){
links[i].className += classes[0];
} else if ( links[i].getAttribute('href').indexOf('b') > -1 ){
links[i].className += classes[1];
}
}
}
Used like this:
var topLinks = document.querySelectorAll('.navUtility-listItem a');
var bottomLinks = document.querySelectorAll('.footerMain-listPlatformItem a');
setClasses(topLinks, [' top-nav-a', ' top-nav-b']);
setClasses(bottomLinks , [' bottom-nav-a', ' bottom-nav-b']);
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
answered Aug 17, 2016 at 17:06
default