0

There are other questions about append, but this is specifically about tag order. The function works fine for content, but seems to close tags before it opens new ones. In this code the words are placed correctly but the p tag is not within the span tag.

html:

<div></div>

js:

$(document).ready(function () {
        $("div").append('<span>begin');
        $("div").append('<p>middle</p>');
        $("div").append('end</span> ');
});

http://jsfiddle.net/dpXv2/1

I want to use a loop to create multiple p's inside the span, how can I get around this?

Edit: http://jsfiddle.net/dpXv2/3/ This should be a little clearer, and I removed the p tag.

Lableable
  • 89
  • 9
  • Spans can't contain p elements. – j08691 Jul 18 '14 at 17:06
  • Try this, `$("div").append('begin

    middle

    end
    ');`. And again, `p` cannot be child of `span`
    – Jashwant Jul 18 '14 at 17:12
  • @Jashwant That would work, but I need to add loops to generate the content, this example is just stripped down to illustrate the problem – Lableable Jul 18 '14 at 17:15
  • Duplicate of this question where I have written a detailed answer: http://stackoverflow.com/questions/21498057/how-to-prevent-jquery-append-function-from-automatically-closing-a-p-with/21502950 –  Jul 18 '14 at 17:20
  • @WumpusQ.Wumbley Thanks, didn't see that one – Lableable Jul 18 '14 at 17:21

2 Answers2

0

Your example is working fine. I'm not sure what you're asking.

Depending on the browser, they sometimes add closing tags to the page if

  • There is no closing tag
  • The tag within the parent is not allowed within that particular parent tag

Furthermore, I don't think you can put a p within a span, but you can put a span within a p.

span is meant to be used within p tags for any styling pertaining to that piece of code.

dartanian300
  • 247
  • 2
  • 16
0

You need to append the p's to the span. for example

$("div").append('<span>begin</span>');
$("div span").append('<p>middle</p>');
$("div span").after('end');

This is because the append adds the full tag when you add your first span.

EDIT: My mistake, the after puts the 'end; text after the span - obviously. You could use:

$("div span").html($("div span").html()+'end');

instead

wolffer-east
  • 1,065
  • 7
  • 14
  • Ok, this works, but it's going to be a little more cumbersome; is there a way to not have it auto-complete the tag? – Lableable Jul 18 '14 at 17:17
  • Not that I know of, it looks like the browser is even auto completing incomplete tags added using .html() – wolffer-east Jul 18 '14 at 17:22