1

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,

http://jsfiddle.net/gL9GR/

Jay Blanchard
34.5k17 gold badges82 silver badges130 bronze badges
asked Feb 27, 2014 at 15:40

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

3 Comments

May I know why filter on direct <div class='ooo'>old message</div> not working ? it seem that find has a bug
Yes, it works, but why find not works on sample one?, do you know ?
@Ata find() will not work because it searches for an descendant element but in your template there are no descendants matching the given selector

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.