-1

Can someone explain why this

x = document.getElementById('bob').style.display;
x = 'hidden';

doesn't work

but

x = document.getElementById('bob');
x.style.display = 'hidden';

works?

  • 4
    Try to `console.log(x)`. You'll see that #1 is a string value of `style.display` property, while #2 is a reference to `HTMLElement` object. – Kosh Feb 24 '22 at 22:47
  • 1
    you can split the difference `x = document.getElementById('bob').style` ... then `x.display = 'hidden'` - of course `display: hidden` is NOT valid CSS and won't "work" in the sense that it does nothing – Bravo Feb 24 '22 at 22:50
  • 1
    [Duplicate](//google.com/search?q=site:stackoverflow.com+js+var+x+=+document.getElementById+.value+does+not+work) of [If I set `var x = document.getElementById("inputText").value` and update `x`, why doesn’t the value update?](/q/6257984/4642212) (even if nearly impossible to find). – Sebastian Simon Feb 24 '22 at 23:05

1 Answers1

0

So the reason behind this is that in the first example x will return a string value of the display, and changing that will only change the string in you JS code. Whereas in the second example x = to a refrence to and HTML object in the DOM. Changing this variables properties will make a change in the DOM, because it is an HTML element, and not a string.

mythic lisp
  • 59
  • 1
  • 7