Replace HTML Attribute Using jQuery

I had a small project that asked for a URL and a pixel-image to be tracked. Another require­ment was to replace a cer­tain string in it with a time­stamp of some sort.

I opted to using the fol­low­ing to get the timestamp:

var timestamp = new Date().getTime();

get­Time() — Will print out the num­ber of mil­lisec­onds since 1/1/1970 @ 12:00 AM.

The links, both for href (A-tag) and src (IMG-tag), will be in some type of the fol­low­ing format:

http://domain.com/subfolder/1924162/[timestamp]?

Know­ing this, we just have to iden­tify which anchors (A-tags) and images would need to be tracked, and time­stamped accord­ingly. I just tagged these with a class called “track­ing”. Now that this is set, we can just use the $ func­tion to gather up the ele­ments that needed to be tracked.

I just then used the fol­low­ing func­tion replaceAttr to switch out the attribute with the gen­er­ated time­stamp:1

jQuery.fn.replaceAttr = function(aName, rxString, repString) {
    return this.attr(
        aName,
        function() {
            return jQuery(this).attr(aName).replace(rxString, repString);
        }
    ); 
};

With that, I just inserted the fol­low­ing in a JS file:

$(function() {
    $("a.tracking").each(function() {
        return $(this).replaceAttr('href', '[timestamp]', timestamp);
    });
    $("img.tracking").each(function() {
        $(this).replaceAttr('src', '[timestamp]', timestamp);
    });
});

When the doc­u­ment is loaded, this will replace the respec­tive links and pixel-images with a timestamp. 

  1. It seems that some­one else were in need of this func­tion. Here’s the page for ref­er­ence. []

2 Comments

Comments Feed · Trackback Address

Leave a Comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>