2

It seems that this code is working well. Please try it out before you answer:

    <!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p>In this example, x, y, and z are variables.</p>
<p id="demo"></p>
<script>
let x = 7;
let y = 45;
let z = x + y;
demo.innerHTML = "The value of z is: " + z;//please note this line
</script>
</body>
</html>

Does this mean that I can replace document.getElementById("id"). with just id.???

  • You can't replace `document.getElementById("id")` with just `id` – byxor May 15 '22 at 17:34
  • It's working. So interesting – Yahya Altintop May 15 '22 at 17:37
  • Yes it is. with all methods and not only with innerHTML. I haven't tested all browsers. Anyone know why is this happening? Is there a trap? I am a teacher. I have a class now with pupils that we re discussing getElementById. Do I tell them this??? – user3771368 May 15 '22 at 17:49
  • The id's of the elements are added to the global `window` object - when you write `demo` it's the same as writing `window.demo` - but there are pitfalls, and edge-cases, so it's very rare to see it being used – Drenai May 16 '22 at 16:02

2 Answers2

0

It's working but it's considered legacy and unsafe.

xijdk
  • 450
  • 4
  • 8
0

Seems like it does, and it works for nested elements also... I wonder though if it works on a different js file imported from the html.

<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Variables</h2>
<p>In this example, x, y, and z are variables.</p>
<p id="demo1">
  <p id="demo2"></p>
</p>
<p id="demo"></p>
<script>
let x = 7;
let y = 45;
let z = x + y;
demo.innerHTML = "The value of z is: " + z;//please note this line

demo2.innerHTML = "The value of z is: " + z;//please note this line
console.log(demo);
</script>
</body>
</html>