0

Only direct assignment of css styles work. passing via user defined variables is not working.Is it a syntax error or css styles cant be passed via user defined variables

<!-- using variable doesnt work -->
<body>
<p id="ref" onclick="display()">hello</p>
<script>
function display(){
var d = document.getElementById("ref").style.display;
d = "none";
}
</script>
</body>

<!-- direct assignment works -->
<body>
<p id="ref" onclick="display()">hello</p>
<script>
function display(){
document.getElementById("ref").style.display = "none";
}
</script>
</body>
Sagi_Avinash_Varma
  • 1,489
  • 11
  • 23
  • possible duplicate of [Is JavaScript a pass-by-reference or pass-by-value language?](http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – Phil Feb 17 '14 at 04:33

3 Answers3

1

style.display is not an object. It's a property of an object and there is no way to directly store a reference to a property.

So, when you do:

var d = document.getElementById("ref").style.display;
d = "none";

All, you're doing is storing the string "none" into the variable d. It isn't doing anything more than that.

Because style is an object, you can have a reference to it:

var s = document.getElementById("ref").style;
s.display = "none";

Though, other than exploring how things work here, there's no reason to use an intermediate variable at all here. So, you may as well just simplify the code and do:

document.getElementById("ref").style.display = "none";

A reference worth reading: Javascript by reference vs. by value

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

That's normal. It has to do with value versus references. When you did var d = document.getElementById("ref").style.display;, you created a copy of the value in a new variable. This means that style.display and d were then two variables with simply the same value. So after that, when you changed the value of d, the value of the other copy remained unchanged. That's why scenario 1 doesn't work, but scenario 2 does.

Here is a Stackoverflow topic that goes much deeper than what I explained : Javascript by reference vs. by value.

Community
  • 1
  • 1
gretro
  • 1,934
  • 15
  • 25
1

Here you are setting the value of the property "display" in variable "d" so "d" contains text value like "none","block","inline-block" etc. not object of an element. so you can't set property via variables.

Sohil Desai
  • 2,940
  • 5
  • 23
  • 35