function $(id) { return document.getElementById(id); }
$('h').innerHTML.replace(/hello/g, "<span style='color: red;'>hello</span>");
It doesn't work. What happened?
-
ummm you have an html element with id=h?Naftali– Naftali2011年05月11日 18:42:18 +00:00Commented May 11, 2011 at 18:42
5 Answers 5
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
Dustin Laine
38.7k10 gold badges90 silver badges125 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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
dlev
48.7k5 gold badges127 silver badges133 bronze badges
Comments
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
slandau
24.2k43 gold badges125 silver badges186 bronze badges
Comments
You're not assigning the value back to the element.
answered May 11, 2011 at 18:44
Tejs
41.4k10 gold badges71 silver badges89 bronze badges
Comments
Try doing this:
function $(id) { return document.getElementById(id); }
$('h').innerHTML = $('h').innerHTML.replace("hello", "<span style='color: red;'>hello</span>");
answered May 11, 2011 at 18:44
Naftali
147k41 gold badges247 silver badges304 bronze badges
Comments
lang-js