0
\$\begingroup\$

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
\$\endgroup\$
1
  • \$\begingroup\$ Can you add corresponding HTML code too \$\endgroup\$ Commented Aug 19, 2016 at 12:00

1 Answer 1

3
\$\begingroup\$

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
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.