Insert a whole element into another element, not just its inner HTML
I'm trying to figure out how to use jQuery to construct HTML as sanely as possible. As far as I can tell, this should produce <div><span>Alice</span></div>
, but instead produces <div>[object Object]</div>
:
post = $("<div>");
username = $("<span>").html("Alice");
post.append(username);
I've found that replacing the last line with post.append(username.html())
gets me closer to my goal, but it omits the <span>
tags if I do it that way. How do I insert a child element with the surrounding tags, and without writing out "<span>" + username + "</span>"
, which seems like a novice approach to the task?
EDIT: Stupid mistake. The snippet I posted above was excessively simplified; I was really trying to do post.append(username + another_span_element)
in my code. Obviously I can't append 开发者_如何转开发objects like that. I've changed it to post.append(username); post.append(another_span_element);
and now it works fine. Durr!
Works for me: $("<div>").append($("<span>").html("Alice"))[0].outerHTML == "<div><span>Alice</span></div>"
What you're aiming for is done with the text() method:
post = $("<div>");
username = $("<span>").text("Alice");
post.append(username);
Example here.
Is there a reason for not doing:
$('<div><span>Alice</span></div>').appendTo('body');
or
var username = "Alice";
$('<div><span id="user"></span></div>').appendTo('body');
$(username).appendTo('#user');
or
var username = "Alice";
$('<div><span id="user"></span></div>').appendTo('body');
$('#user').html(username);
or
var username = "Alice";
$('<div><span id="user"></span></div>').appendTo('body');
$('#user').text(username);
or any of the other 200 options?
精彩评论