Ricardo Müller Ricardo Müller - 4 months ago 12
HTML Question

hyperlink alternate text replacement

At the moment i've got this code, which replaces a span class whith a hyperlink. The hyperlink includes a abbreviation and the alternate texxt for the hyperlink includes the same abbreviation. Now what i want to do is, to somehow replace the second abbreviation in the alternate text of the hyperlink. So that there isn't "click here to visit + 'name of'abbreviation" but instead an alias. So if the abbreviaton is ggl, the alias should be google. But the hyperlink shouldn't use this alias. Can sb help me? thx

(function($) {
var number = "1234567";

function linkBuilder(abbreviation) {
return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + abbreviation + "</a>";
}

function linkBuilder2(abbreviation2) {
return "<a href='https://www.test.com/" + abbreviation2 + "?sitenumber=" + number + "default'>Click here to visit " + abbreviation2 + "</a>";
}
jQuery(document).ready(function() {
var fl = $(".first-link");
if (fl.length > 0) {
fl.html(linkBuilder(fl.data("abbreviation")));
}
var sl = $(".second-link");
if (sl.length > 0) {
sl.html(linkBuilder2(sl.data("abbreviation2")));
}
});
})(jQuery);

Answer

Here is a working jsfiddle:

https://jsfiddle.net/e7qdx031/1/

linkBuilder() should be re-usable, as kalsowerus mentioned.

Another thing that should be mentioned is that the following code returns a collection of elements, not just a single element.

var fl = $(".first-link");
...
var sl = $(".second-link");

The code you have provided will not function properly if there are multiple .first-link classes on the page. So instead I would iterate over each element using $.each() and run the linkBuilder() function on them individually.

As for the linkBuilder function I would modify it to accept the element object, then read the properties to retrieve alias and name. Full name is something that you seemed to indicate you need, but was not present in the code.

(function($) {
    var number = "123456";

    function linkBuilder($obj) {
        var abbreviation = $obj.data('abbreviation');
        var name = $obj.data('name');
        return "<a href='https://www.test.com/" + abbreviation + "?sitenumber=" + number + "default'>Click here to visit " + name + "</a>";
    }

    jQuery(document).ready(function() {
        $('.first-link, .second-link').each(function(index, obj){
            $(obj).html(linkBuilder($(obj)));
        });
    });
})(jQuery);
Comments