Search code examples
javascriptjqueryjquery-1.4

Unable to add attribute on dom ready using jquery


I have the code here on jsfiddle.

We are using jquery 1.4.4 unable to update to newer version as of yet, where I can get my code to work.

So I need to on domready or on pageload, add attr to numerous <a tags. Can someone help me figure out a method where this is possible with javascript and/or the required version of jquery.

Thank you.


Solution

  • You can use .attr(index, callback) process to do it easily like below:

    $('a').attr('href', function(index, oldAttr) {
        if (oldAttr.indexOf('test') >= 0) {
            $(this)
                .removeAttr('onclick')
                .get(0)
                .setAttribute("onclick", "test");
        }
    });​
    

    Demo

    But if you want to use .each() then try like following:

    $('a').each(function(index, element) {
        var el = $(element),
            hasHref = !el.attr('href'); // return true, if no href
        if( !hasHref ) {
            var href = el.attr('href'); 
            if( href.match('test').length || href.match('test-page').length ) {
             el
               .removeAttr("onclick")
               .get(0)
               .setAttribute("onclick", "test");
            }
        }
    });​
    

    Demo