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>
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
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 .
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.