Reputation: 425
I'm learning Javascript and curious about the following distinction I've just discovered. I'll use this page as an example. Take the upvote counter. It's class is .vote-count-post
, and to edit this using parseInt
I've done the following:
var voteA = document.querySelector('.vote-count-post')
voteA.innerHTML = parseInt(voteA.innerHTML) + 1
This successfully adds one to the vote counter, both as a return in the console, and within the DOM.
While observing this I noticed that vote.innerHTML
occurred twice, so I wondered if that could instead be assigned a variable to avoid duplicate typing. Thus I wrote a new variable to test this:
var voteB = document.querySelector('.vote-count-post').innerHTML
voteB = parseInt(voteB) + 1
After entering this, the console returns an increase in the value of voteB, but it does not update the innerHTML in the visual on the DOM. I don't understand why, and wonder if this a fundamental/simple aspect of JS I don't yet comprehend. Could anyone help explain this?
Upvotes: 0
Views: 55
Reputation: 5387
voteB
is a copy of the value of the innerHTML at the time you assign a value to it.
If the value changes, voteB
won't update because it is just a copy of the value at the time of assignment. See here for more info.
Upvotes: 1