0

I have the following HTML:

<html>
    <body>
      <b /> <br>
      Lets say it again: <b /> <br>
    </body>

    <script>
       // this runs after document has already been loaded
       if (document.getElementsByTagName('b').length > 0) {
          Array.from(document.getElementsByTagName('b')).forEach((ele) => {
              ele.innerHTML = "hello world!";
          });
       }
    <script>
</html>

The result is that only the first <b /> gets its innerHTML modified. and NOTHING bellow this gets shown. Inspect shows no further HTML bellow the first <b />

However, if I replace <b /> with <b></b> then everything works just fine.

Any idea why or how it could be fixed? I am using a tag to place a variable and I'd rather it be short as I have quite a few of them.

Thanks!

  • 1
    Use [a validator](https://validator.nu/). The DOM you end up with when a browser attempts to parse that collection of errors is nothing like what you seem to be expecting, which is why the behaviour of the code isn't how you want. – Quentin Mar 12 '21 at 07:55
  • 1
    TL;DR (but the answer that's linked is really good, do read it): `` is not `` in HTML, `` is just like `` (due to error recovery in the parser). If you want ``, write ``. (HTML is not the same as JSX or XHTML.) Side note: `script` elements aren't allowed as direct children of `html` elements. They have to be in `head` or `body`. – T.J. Crowder Mar 12 '21 at 08:07
  • 1
    @Quentin - FWIW, "that collection of errors" reads a bit harsh from a stranger on the 'net. :-) **I** know and you know that you don't mean it unkindly, but... – T.J. Crowder Mar 12 '21 at 08:08
  • Thanks all. And Quentin - all taken with a smile :-) – Avi Boteach Mar 12 '21 at 09:27

0 Answers0