How to append a <ul>
tag inside a <p>
or <span>
?
You can't, it's invalid. So what you're seeing is the browser trying to rearrange it to make it valid.
The content model of span
elements (e.g., what they're allowed to have in them) is "phrasing content" (things like em
and such). (Same for p
elements.) ul
elements are only valid where "flow content" (like paragraphs and divs) is expected.
To fix it, don't try to put a ul
inside a span
or a p
. You could remove the span
and the p
and use a div
, for instance:
$('body').append('<div><ul><li>test</li></ul></div>');
...or just use the ul
directly without a wrapper around it.
Re your update:
If you add the following markup to an html document
...
And then open the page in your favorite browser, it will open correctly. Try it!
Sure — because the browser rearranges it. For instance, this snippet:
<p>
<span>
<ul>
<li>test</li>
</ul>
</span>
</p>
Is turned into this DOM by Chrome:

Note how the ul
is not inside the p
or span
— it's exactly the result you said you were getting.
That said, browsers do a lot to try to tolerate invalid markup and structures. But using valid markup and structures is generally the way to go.
tag can't contain