Replace HTML Attribute Using jQuery

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

I opt­ed to using the fol­low­ing to get the time­stamp:

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 for­mat:

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

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

I just then used the fol­low­ing func­tion replaceAt­tr to switch out the attribute with the gen­er­at­ed 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 insert­ed 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 pix­el-images with a time­stamp.

  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