0

If there is an HTML element with id="hello123", then this JS code prints the content of the element: console.log(hello123.innterHTML)

console.log(hello123.innerHTML);
<p id="hello123">hello this works 123</p>

I discovered this by happenstance, I would other wise have written:

hello123 = document.getElementById("hello123);
console.log(hello123.innerHTML);

What is the difference between the two? Is using getElementById better because it protects be in the case that hello123 is a variable already defined elsewhere that has nothing to do with an HTML element called hello123?

  • 1
    Try adding `const hello123 = "world"` and see what happens. Or try `

    – VLAZ Jun 23 '22 at 17:08
  • Ok, hello-world.innerHTML does not work (returns "hello is not defined"). And I guess your first example was to show that if a variable with the same name already exists, then this does not work (returns undefined)? – Alexandre d'Entraigues Jun 23 '22 at 17:10
  • @Alexandred'Entraigues That's because [`innerHTML`](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML) is a DOM property of a DOM object. See my answer below. – Scott Marcus Jun 23 '22 at 17:11
  • 1
    That's because `hello-world` is an expression meaning "subtract the value of the identifier `world` from the value of the identifier `hello`". Same as how you'd have `4 - 3` or `a - b`. Basically the same problem with `hello-world.innerHTML` but it's the value of the `innerHTML` property of the `world` identifier` that's taken. – VLAZ Jun 23 '22 at 17:13
  • and https://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-properties – James Jun 23 '22 at 17:34

1 Answers1

1

Elements with an id become Global properties of the window object in the Browser's Object Model (BOM). It is not "JavaScript" that makes this happen. Accessing an element with getElementById() uses the Document Object Model (DOM) API, which is standardized. The BOM is largely not standardized. Using the DOM is the best practice.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71