david
david

Reputation: 11

Trouble replacing text with JavaScript. Please help

function $(id) { return document.getElementById(id); }

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

It doesn't work. What happened?

Upvotes: 1

Views: 55

Answers (5)

Naftali
Naftali

Reputation: 146302

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/

Upvotes: 0

Tejs
Tejs

Reputation: 41236

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

Upvotes: 0

slandau
slandau

Reputation: 24052

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.

Upvotes: 0

Dustin Laine
Dustin Laine

Reputation: 38503

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>");

Upvotes: 4

dlev
dlev

Reputation: 48596

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

Upvotes: 3

Related Questions