views:

97

answers:

2

I am new to Prototype and was wondering how to simply "find" some text in a class/ID and "replace" this text.

My html is like this:

<div id="test">
  <a href="/test">test</a>
  <a href="/test2">test2</a>
  <a href="/test3">test3</a>
  <a href="/test4">test4</a>
</div>

And I am trying to replace the "test" in between the <a> tags for the first <a> with the word "success" and the second <a> with "success2". So it would look like

<div id="test">
      <a href="/test">Login</a>
      <a href="/test2">Register</a>
      <a href="/test3">Bla</a>
      <a href="/test4">Logout</a>
    </div>

Any ideas how to do this ?

A: 

With DOM

var x=document.getElementById("test");
for(var i in x.childNodes){
    if(x.childNodes[i].tagName=='A'){
        x.childNodes[i].innerHTML=x.childNodes[i].innerHTML.replace(/test/,'success');
    }
}
S.Mark
hey s.mark - thanks a lot. this changes the "first" <a> but how would I go about changing the 2nd or 3rd with different text ? [thanks so much again!]
John
um, its for both actually, its looping all the childNodes, which include both a tag.
S.Mark
ah :) if the word in the 2nd <a> isn't "success" how would i do it ? i.e. if it was "success" and "donkey" for example ?
John
2nd and 3rd with different text? you may need to count it 1st, 2nd, 3rd inside the loop, and will probably need 3 `if` conditions for each.
S.Mark
so like this ?if(x.childNodes[1].tagName=='A'){ x.childNodes[1].innerHTML=x.childNodes[1].innerHTML.replace(/test/,'success'); }i edited html to show what i mean ? :)
John
Added another answer, since you need different approach
S.Mark
A: 

Here is a different approach using getElementsByTagName

var r=[['Login','success'],['Register','donkey'],['Bla','...'],['Logout','Are you sure?']];
var x=document.getElementById("test");
var a=x.getElementsByTagName("a");
for(i in a){
    a[i].innerHTML=a[i].innerHTML.replace(r[i][0],r[i][1]);
}
S.Mark
hey thanks so much!
John
you're welcome :-)
S.Mark