Search code examples
javascriptyui

Add a class to the current active link using YUI


I got this function in jQuery:

jQuery(function() {
  jQuery('.primary-nav li').each(function() {
    var href = jQuery(this).find('a').attr('href');
    if (href === window.location.pathname) {
    jQuery(this).addClass('current');
    }
  });
});  

but unfortunately I need to do accomplish the same with the YUI library. Add a class to the a element if the a href is the same as the current active page.

Thanks a lot!


Solution

  • An almost direct translation of the JQuery above would be something like:

    YUI().use('node', function(){
        Y.all('.primary-nav li').each(function(node){
            var href = node.getAttribute('href');
            if (href === window.location.pathname){
                node.addClass('current');
            }
        });
    });
    

    However, I would imagine you could do something like:

    YUI().use('node', function(){
        Y.one('.primary-nav li a[href="' + window.location.pathname + '"]').addClass('current');
    });
    

    To achieve the same effect. (code tested only in my head)