JoshR
JoshR

Reputation: 471

How can I include newlines when using appendTo(), insertAfter(), etc?

Suppose I want to add several DIVs to a container, like in this over-simplified example:

for(var x=0; x<3; x++) {
  $("<div>"+x+"</div>").appendTo("#parent");
}

The result (when viewing source) would be something like this:

<div id="parent"><div>0</div><div>1</div><div>2</div></div>

Similarly, the result of $("#parent").html() would be this:

<div>0</div><div>1</div><div>2</div>

But what if I want the source to look like this: (nevermind proper indentation)

<div id="parent">
<div>0</div>
<div>1</div>
<div>2</div>
</div>

So that the result of $("#parent").html() would instead be this:

<div>0</div>
<div>1</div>
<div>2</div>

I thought this would work, but the newline was ignored and wouldn't have accounted for the first linebreak after [div id="parent"] anyway.

for(var x=0; x<3; x++) {
  $("<div>"+x+"</div>\n").appendTo("#parent");
}

Any suggestions?

One of the reasons for the newline formatting is because the resulting HTML will need to be parsed line by line and converted to XML for storage. To complicate matters, there will be nested DIVs, like this:

<div>
  <div>0</div>
  <div>1</div>
</div>
<div>
  <div>2</div>
</div>

Without linebreaks, the above would have to be parsed as this:

<div><div>0</div><div>1</div></div><div><div>2</div></div>

If parsing the single line of HTML above is easier than inserting a bunch of newlines, then I'm all ears for the how-to and would actually prefer that!

Upvotes: 0

Views: 265

Answers (3)

charlietfl
charlietfl

Reputation: 171698

If you are really bothered by it ...generate full strings instead which actually results in less function calls and less appends to the DOM which are expensive

var htm = '';
for(var x=0; x<3; x++) {
  htm+= "<div>" + x + "</div>\n";
}
$("#parent").append(htm);// only one append

You could even add \t for tabbing.

Upvotes: 0

Alvaro Montoro
Alvaro Montoro

Reputation: 29735

Using appendTo does not work, but changing the order and using append actually does work:

Try this:

$("#parent").append("<div>"+x+"</div>\n");

Instead of this:

$("<div>"+x+"</div>").appendTo("#parent");

Upvotes: 0

indubitablee
indubitablee

Reputation: 8216

like this? http://jsfiddle.net/swm53ran/155/

(check the console)

<div id="parent">
</div>

$(document).ready(function() {
    var html = '';
    for(var x=0; x<3; x++) {
      html += "<div>" + x + "</div>\n";
    }
    $('#parent').append(html);
    console.log($("#parent").html());
});

Upvotes: 1

Related Questions