0

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

Loleris54
  • 35
  • 5

2 Answers2

3

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;
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
1

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.

Mitya
  • 33,629
  • 9
  • 60
  • 107
  • Everything is pass by value in JavaScript. But objects are reference-type values, so the value that is passed *is* a reference. That is different from pass *by* reference though. See https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value – Felix Kling Oct 08 '17 at 14:35
  • Interesting. I was unaware of this distinction. Isn't the practical implication the same? The result is the result of the assignment is a reference. Happy to be educated! – Mitya Oct 08 '17 at 16:03
  • 1
    Check out the link if you haven’t already. There is a big difference though. In a true pass by reference language, this would be possible: `var a = 42; var b = a; b = 21; /* a is now 21 */`. Basically “pass by reference/value” describes the relationship between variables and parameters, irrespectively of their values. *but* with reference-type values you can *simulate* pass by reference to some degree (often also called “pass by sharing”). – Felix Kling Oct 08 '17 at 16:08