roberto
roberto

Reputation: 33

JQuery Append function automatically close Div

I use this code to append some html to a div:

 $("#conversazione").append("<div class=\"col-md-6\"></div>");
 $("#conversazione").append("<div class=\"col-md-6\">");
 $("#conversazione").append("<div class=\"col-md-6\" style=\"text-align:right;\">");
 $("#conversazione").append("<img src=\"../img/Conversazione/viso.png\" style=\"margin-top:20px;\"/></div>");
 $("#conversazione").append("<div class=\"col-md-6\" style=\"text-align:left;\">");
 $("#conversazione").append("<div class=\"bubbleUser\">"+message+"</div>");
 $("#conversazione").append("</div></div>");

But when i see the page all are automatically closed. The result is this imageresultOfAppend

How can i have the result i need?

Thanks to all

Upvotes: 0

Views: 851

Answers (2)

madalinivascu
madalinivascu

Reputation: 32354

The browser closes the invalid HTMLs.

Try the following:

 $("#conversazione").append("<div class=\"col-md-6\"></div><div class=\"col-md-6\"><div class=\"col-md-6\" style=\"text-align:right;\"><img src=\"../img/Conversazione/viso.png\" style=\"margin-top:20px;\"/></div><div class=\"col-md-6\" style=\"text-align:left;\"><div class=\"bubbleUser\">"+message+"</div></div></div>");

Upvotes: 3

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

The function .append() directly enters the HTMLDom, so any unclosed DOMString are completed by the browser. So you need to make sure you give complete code. It is better to precompile the HTML as a string and then use .append() like this:

var finalHTML = "<div class=\"col-md-6\"></div>";
finalHTML += "<div class=\"col-md-6\">";
finalHTML += "<div class=\"col-md-6\" style=\"text-align:right;\">";
finalHTML += "<img src=\"../img/Conversazione/viso.png\" style=\"margin-top:20px;\"/></div>";
finalHTML += "<div class=\"col-md-6\" style=\"text-align:left;\">";
finalHTML += "<div class=\"bubbleUser\">"+message+"</div>";
finalHTML += "</div></div>";
$("#conversazione").append(finalHTML);

This applies for .append(), .prepend(), .html(). Also, these functions are heavy in DOM Manipulation. Keep DOM Manipulation to the minimum for performance aspects.

This is same like how browsers convert invalid HTMLs to valid ones. :)

Upvotes: 2

Related Questions