简体   繁体   中英

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); post.append(username); post.append(another_span_element); and now it works fine. Durr!

为我工作: $("<div>").append($("<span>").html("Alice"))[0].outerHTML == "<div><span>Alice</span></div>"

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?

What you're aiming for is done with the text() method:

post = $("<div>");
username = $("<span>").text("Alice");
post.append(username);

Example here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM