Search code examples
javascriptgetelementsbytagname

Can I embed <PRE> tag into <P> tag?


why are there two elements of <p> when i use only one <p> tag?

if <center> tag is instead of <pre>,the result is the same.

if <b> tag is instead of <pre>,the result of a.length is 1.

<!DOCTYPE html>
<html>
<head>

</head>
<body>
  <p><pre>name: id:</pre></p>
<script>
  a = document.getElementsByTagName("p");
  document.write("LEN:"+a.length+"<BR>");
  for(i=0;i<a.length;i++){
    document.write(a[i].innerHTML+"<BR>");
  }
</script>


Solution

  • <pre> cannot be inside <p>. Thus, when the HTML parser encounters <pre> inside <p>, it will close <p> first. Then it encounters </p>, a closing tag without an opening tag, and assumes you wanted <p>. The resulting structure is:

    <p></p>
    <pre>...</pre>
    <p></p>
    

    How do you know <pre> cannot be inside <p>? See <p> on MDN, or even better in HTML spec, and notice "Permitted content: Phrasing content". Looking at what "phrasing content" is, you can see that it does not include <pre>.