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.

asked Jul 13, 2010 at 14:07
1
  • It is working, but you are not setting the value to anything. Commented 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!

answered Jul 13, 2010 at 14:08
Sign up to request clarification or add additional context in comments.

1 Comment

@thomas: Hey, your question is already rank 4 over at Google with meder's search terms ;-)
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');
answered Jul 13, 2010 at 14:10

1 Comment

Caution with use of innerHTML as it's still not officially part of the dom (although it should).
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.

answered Jul 13, 2010 at 14:10

Comments

0

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

answered Jul 13, 2010 at 14:13

Comments

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');
answered Jul 13, 2010 at 14:14

Comments

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

answered Jul 13, 2010 at 14:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.