0

Below, I have a piece of javascript code.

var htmlBlurb = '<div> hello <font color=red>world</font>!!!</div>';
$(htmlBlurb).find('font').each(function(e){
    $(this).html("Javascript");
});
console.log(htmlBlurb);

I am expecting the output in htmlBlurb as

<div> hello <font color=red>Javascript</font>!!!</div>

But htmlBlurb is not changed.

Can someone explain what am I missing here?

Gray
  • 7,050
  • 2
  • 29
  • 52
javaMan
  • 6,352
  • 20
  • 67
  • 94
  • 6
    you never stored the result of `$(htmlBlurb)` to `htmlBlurb`, therefore it's just a string – Kevin B Oct 07 '13 at 17:42
  • 2
    Please don't use the `` element; it was deprecated a looong time ago. – j08691 Oct 07 '13 at 17:43
  • 3
    But they go great with `` – AlienWebguy Oct 07 '13 at 17:51
  • htmlBlurb is not a proper selector, it is just a string. You need to add a class like .hello to your html and use that in the jQuery selector. Right now your not selecting anything to manipulate. – bradcush Oct 07 '13 at 17:52
  • 1
    @bradcush it wasn't intended to be a selector, it's an html string which is perfectly valid for passing to `jQuery()` – Kevin B Oct 07 '13 at 18:07

1 Answers1

2

htmlBlurb is a string. While $(htmlBlurb) creates an element and stores it temporarily, it does not modify the original string, just like running operations on $('a') does not modify the string literal 'a'.

Instead, do the following:

var htmlBlurb = '<div> hello <font color=red>world</font>!!!</div>';
var blurb=$(htmlBlurb)
blurb.find('font').each(function(e){
    $(this).html("Javascript");
});
console.log(blurb.wrapAll('<div></div>').parent().html());
Manishearth
  • 14,882
  • 8
  • 59
  • 76