1
function $(id) { return document.getElementById(id); }
$('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");

It doesn't work. What happened?

asked May 11, 2011 at 18:40
1
  • ummm you have an html element with id=h? Commented May 11, 2011 at 18:42

5 Answers 5

4

replace returns a string and does not automatically assign it to the element.

$('h').innerHTML = $('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
answered May 11, 2011 at 18:43
Sign up to request clarification or add additional context in comments.

Comments

3

replace() does not happen in-place; you need to assign the result to the destination you want:

var newText = $('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
// Do something with newText
answered May 11, 2011 at 18:43

Comments

0

First of all, you don't need your first function, JQuery takes care of that automatically via a selector. Also, setting innerHTML should replace all the existing content of it anyway, so you don't need to explicitly state replace after that.

$('#h').html(/hello/g, "<span style='color: red;'>hello</span>");

Also, I think your quotes were wrong.

answered May 11, 2011 at 18:44

Comments

0

You're not assigning the value back to the element.

answered May 11, 2011 at 18:44

Comments

0

Try doing this:

function $(id) { return document.getElementById(id); }
$('h').innerHTML = $('h').innerHTML.replace("hello", "<span style='color: red;'>hello</span>");

fiddle: http://jsfiddle.net/maniator/LBAn6/

answered May 11, 2011 at 18:44

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.