I want to create a dynamic element in javascript and change the content and append that to the body, buy not works
var template = "<div class='ooo'>old message</div>";
$(template).find(".ooo").html("new message");
$("body").append(template);
it return old message , it seem that JQUERY directly work with internal DOM,
Jay Blanchard
34.5k17 gold badges82 silver badges130 bronze badges
asked Feb 27, 2014 at 15:40
Ata
12.7k20 gold badges71 silver badges101 bronze badges
1 Answer 1
Modifying the jQuery object will not update the string literal from which it was created
var template = "<div class='ooo'>old message</div>";
var $tmpl = $(template);
$tmpl.filter(".ooo").html("new message");
$("body").append($tmpl);
Demo: Fiddle
Also in the given template you need to use .filter() instead of .find() because $tmpl refers to the .ooo element - you can even completely remove that because there is only one element in $tmpl
answered Feb 27, 2014 at 15:42
Arun P Johny
389k68 gold badges533 silver badges532 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Ata
May I know why filter on direct <div class='ooo'>old message</div> not working ? it seem that find has a bug
Ata
Yes, it works, but why find not works on sample one?, do you know ?
Arun P Johny
@Ata
find() will not work because it searches for an descendant element but in your template there are no descendants matching the given selectorlang-js