Reputation: 45
I'm trying to update number of people connected to the site by changing html element using javascript. For some reason if I set a variable on it, it does not work, but if I do it raw way (w/o variable) it works fine.
var users = document.getElementById('users').innerHTML;
users = connection.users;
↑ Doesn't Work
document.getElementById('users').innerHTML = connection.users;
↑ Works
Upvotes: 0
Views: 87
Reputation: 34556
This is happening because the value assigned to users
is a string - assigned by value, i.e. copied. It is not a stay-alive reference to the innerHTML
property of an element.
If you want to use a variable, assign it as the element, not its HTML.
var users_el = document.getElementById('users');
users_el.innerHTML = connection.users;
In JavaScript, complex objects are copied by reference, whereas simple data types are copied by value, as in your case.
Upvotes: 1
Reputation: 36311
This doesn't work because you are setting the innerHTML to the variable which isn't an object.
Doing this should work:
var users = document.getElementById('users');
users.innerHTML = connection.users;
Upvotes: 3