What is the reason for object destructuring not functioning properly in styles?

Why is it that the HTMLelement is considered an object, while the style is also an object, yet this code fails to work as expected? When I remove destructuring, everything functions properly, so I am curious to understand the underlying reason behind this.

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>

Answer №1

When employing destructuring, it essentially generates new local variables, as evidenced by the following code snippet:

let {color, background} = div.style

This can be perceived as being akin to:

let color = div.style.color
let background = div.style.background

Subsequently, should you execute the subsequent lines:

color = "red"
background = "blue"

It is key to note that you are merely updating the values of local variables, rather than creating new object properties.

Answer №2

This:

const changeColor = () => {
  const div = document.querySelector("div");
  let {color, background} = div.style;       // ***
  color = "red";
  background = "blue";
};

is essentially the same as the following, except that div.style is only evaluated once:

const changeColor = () => {
  const div = document.querySelector("div");
  let color = div.style.color;               // ***
  let background = div.style.background;     // ***
  color = "red";
  background = "blue";
};

However, changing the local variable doesn't impact the object property in either scenario. The local variable simply acquires the value of the object property, without establishing a lasting connection back to it.

To put it differently: Destructuring merely establishes local variables, rather than constructing an object that serves as a "view" into the original object for accessing its properties. (While this concept may be intriguing, it is not the purpose of destructuring.)

Alternatively, you can achieve the same result by:

const changeColor = () => {
  const {style} = document.querySelector("div");
  style.color = "red";
  style.background = "blue";
};

This method succeeds by obtaining a reference to the div's style object and directly altering its properties.

Or, if we move away from destructuring entirely:

const changeColor = () => {
  Object.assign(document.querySelector("div").style, {
      color: "red",
      background: "blue"
  });
};

If the function accepts these as arguments, then:

const changeColor = (color, background) => {
  Object.assign(document.querySelector("div").style, {color, background});
};

This function would be invoked using changeColor("red", "blue");.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Instructions for showing a timer on a webpage from a managed bean by utilizing JavaScript

I'm currently tackling the challenge of passing a Date from a managed bean to JavaScript and then displaying it as a timer in the format "hh:mm:ss aa". I've attempted it but so far, no luck. Code: DateTimeManagmentMB.java (Managed Bean) import ...

Visualizing connections between elements using SVG from JSON data files

As a newcomer to D3, I am facing challenges in visualizing my json file. My task involves plotting the locations (sites) as circles with their radius determined by the "amount" value. The concept of working with nodes and links is causing me great confusio ...

What is the correct method for exporting an ES6 module function as a library to be utilized in a Node.js application?

Imagine having a node.js application that does not pass through webpack bundling: Node App const Html = require('./build/ssr-bundle.js'); let result = Html.ssrbundle.render(); console.log(result); Here is my ES6/JSX file, which undergoes web ...

Problems Arising from the Combination of Django and External JavaScript

I am currently working on a project that uses Django 1.11 and JavaScript, but I am encountering an issue. The JavaScript code works fine when run within the HTML file, as it successfully loads the JSON data. However, when I move everything to the static fo ...

In Javascript, we can increment the current date by utilizing the `getDate()`

I am trying to create an if statement in JavaScript; if (nextProcessingDate > today ) { //do something } nextProcessingDate has a timestamp assigned, like 09/07/2014 12:10:17 To assign today's timestamp to the today variable, I am using this c ...

Manipulate JSON objects in AngularJS by deleting or adding items

This JSON is currently in my possession: var videos = [ {"id":"9854", "time": 56}, {"id":"7859", "time": 29}, {"id":"8745", "time": 59} ]; If an item is missing from the JSON, I want to add it, but if it's already there, I want to remove ...

Having trouble reaching an element within a successful Ajax call

I have encountered an issue where the element is not being recognized when putting an ajax call inside another ajax call. Here is an example of the code: $.ajax({ url: 'controleFatAcoes.php', type: 'post', dataType: 'h ...

What is the process for installing fontawesome using npm?

I encountered an error while attempting to install that looks like the following: $ npm install --save @fortawesome/fontawesome-free npm WARN saveError ENOENT: no such file or directory, open 'C:\Users\Admin\Desktop\package.json&a ...

Is there really a need to go through the hassle of creating a pure javascript/jquery widget when I can simply load it into an

Previously, I had a widget with the following code: <script src="http://www.mywebsite.com/widget/widget.js?type=normal" type="text/javascript"></script> <div id="archie-container"></div> This widget checked for the presence of jQu ...

Instructions on transferring input data from a text box to the next page using a session in PHP

Is there a way I can transfer the data from a text box to another page (demo2) and store all the information in my database? I attempted to use sessions, but although the value is being passed to the next page, the text box data isn't... Check out th ...

The dropdown login form is malfunctioning on my Wordpress website

After reading various tutorials and guides online, I managed to set up a login screen. You can view the code in my jsfiddle: Jsfiddle. Unfortunately, I am facing issues with making the code function correctly. Being new to Jquery, I might have made a begin ...

Include a couple of images to the jQuery Slider

I have a website and am looking to incorporate a jQuery slider that meets my needs. However, the current slider only displays 3 pictures. How can I add one or two additional pictures to the slider? Demo: http://d.lanrentuku.com/down/js/jiaodiantu-883/ He ...

Tips for storing an unmatched result in an array with a Regexp

Is it possible to extract the unmatched results from a Regexp and store them in an array (essentially reversing the match)? The following code partially addresses this issue using the replace method: str = 'Lorem ipsum dolor is amet <a id="2" css ...

Managing Dark Mode in Material UI with Redux

Having a React application integrated with Material UI, I encountered an issue with the dark mode functionality. Whenever I attempt to modify the dark mode state on a page where the content is rendered from redux state data, the entire page crashes. It app ...

Issue with delayed chaining of class addition and removal in JQuery not functioning as expected

Here is the code snippet: $(document).ready(function () { $('.current-visitors').delay(3000).queue(function () { $(this).addClass('show').delay(1000).queue(function () { $(this).removeClass('sho ...

Creating an input field within a basic jQuery dialog box is not possible

Can anyone assist me in adding an input box to my dialog box? I am working with jquery-ui.js. Here is the code I currently have: $(document).on("click",".savebtn",function(). { var id = $(this).attr("id"); $.dialog({ ...

Using app.js in a blade file can cause jQuery functions and libraries to malfunction

In my Laravel application, I am facing an issue with my vue.js component of Pusher notification system and the installation of tinymce for blog posts. Adding js/app.js in my main layout blade file causes my tinymce and other jQuery functions to stop workin ...

What is the best way to pick out specific passages of text

I'm attempting to create an autocomplete feature where the data is displayed in a div below the text box as the user types. While this typically involves ajax, I've simplified the approach without using jQuery autocomplete. Once the text appears ...

How can dynamic x and y values be used to create moving waves on Canvas in HTML5?

My dynamic array values consist of x and y... Incorporating these x and y values, I want to create varying sine, triangular, square, and sawtooth waves on an HTML5 canvas... ...

Issues with authenticating PHP password against MYSQL

I've hit a roadblock while working on my project, and I believe it's a simple fix. However, I just can't seem to figure it out. If you want to see the issue for yourself, check out the live site at www.thriftstoresa.com. The problem lies wi ...