1

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.

1
  • It is working, but you are not setting the value to anything.
    – BrunoLM
    Jul 13, 2010 at 14:10

6 Answers 6

4

replace is not a mutator method.

el.nodeValue = el.nodeValue.replace(/regex/,'something');

use it like so...

remember to google.. surprise!

1
  • @thomas: Hey, your question is already rank 4 over at Google with meder's search terms ;-)
    – Boldewyn
    Jul 13, 2010 at 14:35
0

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
  • Caution with use of innerHTML as it's still not officially part of the dom (although it should).
    – gnome
    Jul 13, 2010 at 14:33
0

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.

0

Try this p.childNodes[0].nodeValue=p.childNodes[0].nodeValue.replace(/sql/gi, 'VB.NET');

0

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');
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.