1

I thought this would be simple but this code outputs my spans on the same line.

$("<p/>")
    .append($("<span/>", {
        class:"time",
        text: content.time }))
    .append($("<span/>", {
        class: "content",
        text: content.message
    }));

But since it append these elements without a newline, my spans end up needing manual spacing, which just isn't possible at my current scale.

<p><span class="time">now</span><span class="content">Lorem Ipsum ...</span></p>

How can I force jQuery to manually append my spans on a new line? I've tried using .after to.

EDIT:

I guess I was a bit unclear, so far .append("\n") is what I'm looking for, if there are any better ways, I'm all ears but appending a <br/> tag is definitely not what I was looking for.

<p>
   <span class="time">now</span>
   <span class="content">Lorem Ipsum ...</span>
</p>
user2397965
  • 83
  • 3
  • 7
  • 1
    Append a
    too. Why do you expect append to insert any whitespace or BRs by itself?
    – mplungjan Jul 16 '15 at 20:38
  • 1
    I don't and I guess I was unclear on that. Some elements need the line break in html to display correctly... I don't want the spans rendered on new lines but rather the html to have both spans on separate lines. – user2397965 Jul 16 '15 at 21:45

4 Answers4

2

If you want the HTML element to be appeneded to a newline, you can insert a newline character, \n, using the .after() method before appending the second span. In doing so, there will be a space between the words (since inline span elements respect the whitespace in the markup).

Example Here

$("p").append($("<span/>", {
    class: "time",
    text: content.time
}).after('\n')).append($("<span/>", {
    class: "content",
    text: content.message
}));
Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
1

This should work

$("<p/>")
    .append($("<span/>", {
        class:"time",
        text: content.time }))
    .append("<br/>")
    .append($("<span/>", {
        class: "content",
        text: content.message
    }));
Kristofor
  • 58
  • 10
1

Append line break separately, not by joining it to text, then it works:

$("<p/>")
    .append($("<span/>", {
        class:"time",
        text: content.time }))
    .append($("<br />"))
    .append($("<span/>", {
        class: "content",
        text: content.message
    }))
    .append($("<br />"));

working fiddle

Keammoort
  • 3,075
  • 15
  • 20
0

<span> is inline element. You can change it to block with CSS:

span {
    display: block;
}

or use after pseudoelement:

span::after { 
    content: "\A";
    white-space: pre;
}

or use <br />

alcohol is evil
  • 686
  • 12
  • 34