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!