Is it true that document.getElementById().innerHTML can't be used to insert new html which would disrupt the bracketing it is inner to?

StackOverflow https://stackoverflow.com/questions/22734310

  •  23-06-2023
  •  | 
  •  

Pergunta

I've been mucking around with Javascript for the first time and have found that while you can easily do something like

<p id="demo"> Hello </p>

<script> document.getElementById("demo").innerHTML = "<strong>Hello</strong>"; </script>

and get "Hello". You can't do something like

<p> Hello my name is <strong id="demo">Sam</strong></p>

<script> document.getElementById("demo").innerHTML = "Sam </strong> and <strong> Susan"; </script>

and get "Hello my name is Sam and Susan".

I've had a look at places like w3schools to try to understand this. My best guess is that for whatever reasons .innerHTML can't actually change the "outer" of the element that it's altering. I'd love it if somebody could give me a slightly more clear explanation of this behaviour. I don't think it's something I want to use I'd just like to understand it a little better.

Foi útil?

Solução

Documents don't really work in term of HTML tags. As soon as parsing ends, there is no more HTML, only the DOM structure, which on demand can be translated back to HTML.

In your example the parser looks at the string Sam </strong> and <strong> Susan, sees that it's incomplete and tries to correct it, so you get Sam and <strong> Susan</strong>.

I suppose it could dump the DOM to HTML, replace the innerHTML literally and re-parse the whole thing, but that would be a lot slower with insignificant benefits.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top