Skip to content Skip to sidebar Skip to footer

Javascript - Link Name Changing With Restrictions

I'm trying to change the name of a link, however, I have some restrictions. The link is placed in code that looks like this:
  • Review T
  • Solution 1:

    Solution 2:

    Split the words on space, reverse the order, put back together.

    var j = $('li.time > a');
    var t = j.text();
    var a = t.split(' ');
    var r = a.reverse();
    j.text(r.join(' '));
    

    This could have some nasty consequences in a multilingual situation.

    Solution 3:

    Old school JavaScript:

    functionreplaceLinkText(className, newContents) {
      var items = document.getElementsByTagName('LI');
      for (var i=0; i<items.length; i++) {
        if (items[i].className == className) {
          var a = items[i].getElementsByTagName('A'); 
          if (a[0]) a[0].innerHTML = newContents;
        }
      }
    }
    
    replaceLinkText("time", "Review Time");
    

    Note that modern browsers support getElementsByClassName(), which could simplify things a bit.

    Solution 4:

    You can traverse the DOM and modify the Text with the following JavaScript:

    var li = document.getElementsByClassName('time');
    for (var i = 0; i < li.length; i++) {
       li[i].getElementsByTagName('a')[0].innerText = 'new text';
    }
    

    Demo: http://jsfiddle.net/KFA58/

    Post a Comment for "Javascript - Link Name Changing With Restrictions"