I'm doing something like:
<p>SQL</p>
<p>sql</p>
<p>sQl</p>
<p>SqL</p>
<script type="text/javascript">
var ps = document.getElementsByTagName('p');
for(var i = 0; i < ps.length; i++) {
var p = ps[i];
p.childNodes[0].nodeValue.replace(/sql/gi, 'VB.NET');
p = null;
}
</script>
But it's not replacing the text. What's wrong? Thank you.
-
It is working, but you are not setting the value to anything.BrunoLM– BrunoLM2010年07月13日 14:10:15 +00:00Commented Jul 13, 2010 at 14:10
6 Answers 6
replace is not a mutator method.
el.nodeValue = el.nodeValue.replace(/regex/,'something');
use it like so...
1 Comment
try
p.childNodes[0].nodeValue = p.childNodes[0].nodeValue.replace(/sql/gi, 'VB.NET');
or
p.innerHTML = p.innerHTML.replace(/sql/gi, 'VB.NET');
1 Comment
You are not assigning the replacement back into the p element.
Also remember that alert is your friend. See what's in p.childNodes[0].nodeValue.
Comments
Try this p.childNodes[0].nodeValue=p.childNodes[0].nodeValue.replace(/sql/gi, 'VB.NET');
Comments
I believe replace, here, is simply returning the value (it's been a while).
Have you tried:
p.childNodes[0].nodeValue = p.childNodes[0].nodeValue.replace(/sql/gi, 'VB.NET');
Comments
I would pull that out into a function in the documents head, then call the method before the closing body tag. This will ensure that the document logs before the js executes:
// head
<script type='text/javasript'>
function changeText() {
var ps = document.getElementsByTagName('p');
for(var i = 0; i<ps.length; i++) {
var node = ps[i].childNodes[0].nodeValue.toLowerCase();
node = node.replace('sql', 'VB.NET');
ps[i].childeNodes[0].nodeValue = node;
}
}
</script>
// Before the closing body tag
<script type='text/javascript'>changeText();</script>
You could also using jQuery, here's a find / replace approach, Find & replace jquery