2

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.

the_martian
  • 291
  • 1
  • 12
  • `innerHTML` the name itself says that it is referencing the inner part of that particular element. – ɹɐqʞɐ zoɹǝɟ Mar 29 '14 at 17:31
  • Using innerHtml is never a good idea. http://stackoverflow.com/questions/7476638/if-people-recommend-i-shouldnt-use-innerhtml-what-then-should-i-instead-use – pj013 Mar 29 '14 at 17:33
  • The DOM isn't a string. It doesn't have closing an opening tags. The HTML markup is discarded after the page loads. Any HTML manipulation you do via JS must be complete and valid representations, which then also will be discarded after they've been parsed into DOM elements. – cookie monster Mar 29 '14 at 17:37
  • Thanks all. What I wasn't understanding was the way HTML and documents were related. I thought it would insert the text into the innerHTML then reparse the whole thing. – the_martian Mar 29 '14 at 17:40
  • That's a pretty common misconception. I don't mind a little `.innerHTML` insertion here and there when sensible, but try to avoid adding new content to existing content with `.innerHTML += "...new content..."`. There are much better, safer and more appropriate ways. – cookie monster Mar 29 '14 at 17:43
  • W3schools is a terrible resource. Use MDN – John Dvorak Mar 29 '14 at 17:56

1 Answers1

2

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.

sabof
  • 8,062
  • 4
  • 28
  • 52