-2

I have a troublesome situation: what I want is to reassign the value 'hi' to the x variable, however what I'm currently trying isn't working:

<script>
function hello(){
    let x = document.getElementById("post-title").innerHTML
    x = 'hi'
}
</script>

However, if I do it this way, it works:

document.getElementById("post-title").innerHTML = 'hi'

Why does it not work when using a named variable?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    `x` is just a string. It doesn't keep any reference to the element. You can get the element to `x` and update it's innerHTML: `let x= document.getElementById("post-title"); x.innerHTML = 'hi'` – adiga Jul 02 '21 at 15:38
  • 1
    Does this answer your question? [Setting a variable equal to another variable](https://stackoverflow.com/questions/50840293/setting-a-variable-equal-to-another-variable) – Ivar Jul 02 '21 at 15:39
  • 1
    `x` just holds the retrieved value of the `innerHTML` from the DOM element. Modifying the value of the variable will not affect the element from which it was retrieved. To mutate the DOM, you need to explicitly make calls to mutate it (there is no automatic two-way data binding). You can look into to frameworks like Vue.js or React.js since one of the main functionalities they offer is managing state to keep DOM elements in sync when you make changes to data in your code. – zr0gravity7 Jul 02 '21 at 15:40
  • Using a framework to solve this problem is overkill. – Andy Jul 02 '21 at 15:46
  • 1
    @ MichaelHorn: thanks for wanting to edit questions here. However, we generally remove please-help-me begging, we do not edit it in. Expressions of neediness tend to be discouraged in favour of technical writing. If you are writing in the voice of the original poster, please use "How can I ..." and "What can I ...". – halfer Jul 02 '21 at 22:14
  • 1
    Does this answer your question? [Setting innerHTML: Why won't it update the DOM?](https://stackoverflow.com/questions/8196240/setting-innerhtml-why-wont-it-update-the-dom) – Jahnavi Paliwal Jul 03 '21 at 19:05
  • 1
    @halfer Thank you, I'll remember that for future edits – Michael Horn Jul 05 '21 at 18:30

1 Answers1

1

innerHTML returns a string. So however u update doesnt mean that u update the DOM element html.

U can achieve in these ways.

document.getElementById("post-title").innerHTML = "hi"
x = document.getElementById("post-title")
x.innerHTML = "hi"