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';
    }
}
\$\endgroup\$
1
  • \$\begingroup\$ Can you add corresponding HTML code too \$\endgroup\$
    – Tushar
    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']);
\$\endgroup\$
0

Your Answer

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