The HTMLelement is an object. The style is an object too. So why this code doesn't work? Without destructuring everything works fine, so it isn't a big problem, i just want to know the reason.
const changeColor = () => {
const div = document.querySelector("div");
let {color, background} = div.style;
color = "red";
background = "blue";
}
div{
width: 300px;
height: 150px;
color: blue;
background: red;
}
<div onClick = "changeColor()">
<p>Example</p>
</div>
destructuring just creates new local variables which means that
let {color, background} = div.style
is essentially equivalent to
let color = div.style.color
let background = div.style.background
and if you then follow those lines with
color = "red"
background = "blue"
You have not assigned a new object property to anything, you've only assigned new values for local variables.
This:
const changeColor = () => {
const div = document.querySelector("div");
let {color, background} = div.style; // ***
color = "red";
background = "blue";
};
is exactly the same as this other than that div.style is evaluated once, not twice:
const changeColor = () => {
const div = document.querySelector("div");
let color = div.style.color; // ***
let background = div.style.background; // ***
color = "red";
background = "blue";
};
Changing the local variable doesn't have any effect on the object property in either case. The local variable got the value of the object property, it has no enduring link back to it.
Putting it another way: Destructuring just creates locals, it doesn't create an object that's a kind of "view" onto the original object providing accessors to the original object's properties. (That would be kind of interesting, but it's not what destructuring does.)
You could do this, though:
const changeColor = () => {
const {style} = document.querySelector("div");
style.color = "red";
style.background = "blue";
};
That works because we're grabbing a reference to the div's style object and modifying its properties directly.
Or, leaving destructuring behind entirely:
const changeColor = () => {
Object.assign(document.querySelector("div").style, {
color: "red",
background: "blue"
});
};
and if the function accepts those as parameters, then:
const changeColor = (color, background) => {
Object.assign(document.querySelector("div").style, {color, background});
};
which you'd call via changeColor("red", "blue");.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With