Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append a ul tag inside a P or span tag?

Run the following piece of jQuery:

$('body').append('<p><span><ul><li>test</li></ul></span></p>');

I would expect this:

<p>
  <span>
    <ul>
      <li>test</li>
    </ul>
  </span>
</p>

However, the result is this:

<p>
  <span></span>
</p>
<ul>
  <li>test</li>
</ul>

Why does the ul tag break out of span and p? This is valid HTML markup.

* UPDATE *

The p tag seems to be the problem. If you run the following:

$('body').append('<span><ul><li>test</li></ul></span>');

then

<span>
  <ul>
    <li>test</li>
  </ul>
</span>

will generate properly.

like image 249
Jon Cursi Avatar asked Oct 23 '25 09:10

Jon Cursi


1 Answers

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:

enter image description here

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.

like image 111
T.J. Crowder Avatar answered Oct 25 '25 23:10

T.J. Crowder