开发者

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:

<li class='time'> 
<a href="#time">Review Time</a> 
<img alt="Styled" src="blah" /> 
</li> 

Basically, I have a class name to work with. I'm not allowed to edit anything in these lines, and I only have a header/footer to write Javascript / CSS in. I'm trying to get Revi开发者_运维百科ew Time to show up as Time Review, for example.

I know that I can hide it by using .time{ display: hide} in CSS, but I can't figure out a way to replace the text. The text is also a link, as shown. I've tried a variety of replace functions and such in JS, but I'm either doing it wrong, or it doesn't work.

Any help would be appreciated.


You could get the child elements of the li that has the class name you are looking for, and then change the innerHTML of the anchor tags that you find.

For example:

    var elements = document.getElementsByClassName("time")[0].getElementsByTagName("a");

    for(var i = 0, j = elements.length; i<j; i++){
        elements[i].innerHTML = "Time Review";
    }

Of course, this assumes that there is one element named "time" on the page. You would also need to be careful about checking for nulls.


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.


Old school JavaScript:

function replaceLinkText(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.


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜