Replace HTML Attribute Using jQuery


I had a small project that asked for a URL and a pixel-image to be tracked. Another requirement was to replace a certain string in it with a timestamp of some sort.

I opted to using the following to get the timestamp:

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

getTime() – Will print out the number of milliseconds 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 following format:

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

Knowing this, we just have to identify which anchors (A-tags) and images would need to be tracked, and timestamped accordingly. I just tagged these with a class called “tracking“. Now that this is set, we can just use the $ function to gather up the elements that needed to be tracked.

I just then used the following function replaceAttr to switch out the attribute with the generated timestamp: ((It seems that someone else were in need of this function. Here’s the page for reference.))

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 following 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 document is loaded, this will replace the respective links and pixel-images with a timestamp.