user2397965
user2397965

Reputation: 93

Jquery append() on another line?

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>

Upvotes: 1

Views: 2853

Answers (4)

alcohol is evil
alcohol is evil

Reputation: 704

<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 />

Upvotes: 0

Josh Crozier
Josh Crozier

Reputation: 240948

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
}));

Upvotes: 2

Keammoort
Keammoort

Reputation: 3075

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

Upvotes: 1

Kristofor
Kristofor

Reputation: 58

This should work

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

Upvotes: 1

Related Questions