Search code examples
jqueryjquery-selectorshrefattr

Setting the id of a link based on it's href


$('.portfolioThumbs ul li a').mouseover(
    function(){
        var buttLink = $(this).attr('href') 
        var buttLinkArray = buttLink.split( '/' ); // Split the URL after each / and Create an array of each
        var pFN = buttLinkArray[2]; // We want the Portfolio Folder Name
        var url = window.location.pathname;

        $('.galleryNav ul li a').removeClass('hovered');
        $('.galleryNav ul li a' + '#' + pFN).addClass('hovered');
        window.location.pathname = url + '#' + pFN;
    }       
);

This code allows me to set an ID on each button based on its href when the user "mouseover's" it. Does anyone know how this can be done automatically when the page loads, so that each button in the list gets and ID based on it's href, without any user interaction.

Thanks,

Dan


Solution

  • Iterate through all links on page load. If you are using jQuery 1.7+ then use prop to set the href attribute. Otherwise use attr.

    $('.portfolioThumbs ul li a').each(
        function(){
            var buttLink = $(this).attr('href')  //do you really want attr or do you want prop?
            var buttLinkArray = buttLink.split( '/' ); // Split the URL after each / and Create an array of each
            var pFN = buttLinkArray[2]; // We want the Portfolio Folder Name
            var url = window.location.pathname;
            $(this).prop('href', url);
        }       
    );