Contrasting element.setAttribute and element.style.setProperty differences

I am trying to dynamically change the value of a custom CSS variable using JavaScript. I initially attempted to use

element.style.["--my-custom-var"] = value
, but realized that it did not work for custom variables. After some research, I discovered that I can add custom CSS properties to an element using both element.setAttribute and element.style.setProperty. My question is: what is the difference between these two approaches? Specifically, which method offers better performance and which one is considered best practice when adding custom properties via JavaScript.

Example:

// Both of these code snippets are capable of adding a custom css rule to the inline style of an element
element.setAttribute('style','--my-custom-var: 10px;');
element.style.setProperty('--my-custom-var', '10px');

Answer №1

By setting the style attribute, all other inline style properties of the element are removed.

When using the setProperty() method, only that specific style is replaced.

An interesting observation can be made in the following example: the background color disappears from the first div.

document.getElementById("setstyle").setAttribute("style", "color: red;");
document.getElementById("setprop").style.setProperty("color", "red");
<div id="setstyle" style="background-color: yellow; color: blue;">Setting style</div>
<div id="setprop" style="background-color: yellow; color: blue;">Setting property</div>

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

TypeScript raises an issue with a Vue component property that has been defined using vue-property-decorator

I have a Vue component with a property defined using a decorator: import { Component, Vue } from "vue-property-decorator" @Component({ props: { myId: String, }, }) class TestProp extends Vue { myFuncti ...

Update to the center of the JavaScript map on Google Maps

Hello everyone, While I may not consider myself a JavaScript expert, I often piece together code snippets from various sources to get things done. Currently, I am facing a challenge with styling Google maps as they don't seem to be customizable unles ...

At what moment does the object returned from a get method come into existence?

Exploring the code below: var obj={ prop1:7, get prop2 (){ console.log('I ran'); return {a:1,b:2} } } At what point is the object {a:1,b:2} created? Is it created when the code above is executed, ...

Is there a way to solely adjust the color of a -box-shadow using jquery?

Looking for a way to incorporate tinycolor, a color manipulation framework, into setting a box-shadow color. Instead of directly setting the box-shadow with jQuery, you can use tinycolor on an existing color variable. $("CLASS").css("box-shadow", "VALUE") ...

Firebase functions are giving me a headache with this error message: "TypeError: elements.get is not

Encountering the following error log while executing a firebase function to fetch documents and values from the recentPosts array field. Error: Unknown error status: Error: Unknown error status: TypeError: elements.get is not a function at new HttpsEr ...

Launch Bootstrap 4 Modal using JavaScript with just a simple click on a hyperlink

My goal is to trigger a modal to open when a link is clicked, but unfortunately I am unable to modify the HTML of the link itself. The only thing I can change is the href attribute. For example: <a href="#Modal">Open modal</a> I am not able ...

IE does not support Overflow and Ellipsis in this table

FF v14 has the exact appearance I want. Unfortunately, IE9 is not cooperating as it does not hide overflow or display the ellipsis. Does anyone know how to resolve this issue for compatibility with IE9? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Tran ...

The active class in the Bootstrap carousel is not updating when trying to change

I am struggling to make the Twitter Bootstrap carousel function properly. Although the slides automatically change after the default timeout, the indicators do not switch the active class, resulting in my carousel failing to transition between slides. Ini ...

Problem with executing callback after saving Mongoose model

Currently, I am delving into Node.js by studying a book. Instead of simply copying and pasting the sample code provided in the book, I am taking the concept and incorporating it into my own code as a learning exercise. One specific example is a new user c ...

Transform colored svg:image elements into grayscale when clicked upon by utilizing d3

Visit this site I'm attempting to change all SVG images created using d3.select to grayscale by using the following function: JavaScript: <script> function convert() { d3.selectAll("image") .style('filter', 'graysc ...

The comparison between dynamically adding elements through Javascript and hiding them using CSS

I am contemplating the advantages and disadvantages of adding elements to a page and setting display:none versus creating a function that dynamically generates the elements and appends them where needed. In my current situation, I am implementing a reply ...

Applying the Directive/Isolated Scope as Embedded HTML within an Angular-Bootstrap Popover

If you're using the angular-ui popover, you have the ability to include HTML content within it. However, I encountered some difficulties in placing a directive called sampleDirective inside the popover. Despite my attempts with the $sce.trustAsHtml an ...

Tracking the movement of a handheld device through GPS technology

I am interested in creating a mobile application that can track the real-time location of users who have the app installed on their devices. The concept is to allow one or more users to follow the movement of another user using GPS on a map. I plan to deve ...

Merging multiple observables with RxJs forkJoin

UPDATE : I'm currently facing a challenging issue that I can't seem to resolve. Within my code, there is a list of objects where I need to execute 3 requests sequentially for each object, but these requests can run in parallel for different obje ...

When I attempt to send a PUT request, the req.body object appears to be empty. This issue is occurring even though I have implemented the method override middleware

I am currently facing an issue with updating a form using the put method. To ensure that my form utilizes a PUT request instead of a POST, I have implemented the method override middleware. However, upon checking the req.body through console log, it appear ...

What is the process of defining a route for a JSON response in an Express application?

I've been following an Angular tutorial on handling form submissions with promises, which I found here. My server is running on Node and I'm using Express to manage routes. However, when I submit the form and reach the line var $promise = $http. ...

Include "clickable" commas among various <span> elements

Struggling to insert commas between a series of items? Well, fear not! If you're wondering how, it can be achieved with a simple line of code: .comma:not(:last-of-type)::after{ content: ", "; } <span class="comma">A</span> <s ...

Font size for the PayPal login button

I am looking to adjust the font size of the PayPal Login button in order to make it smaller. However, it appears that the CSS generated by a script at the bottom of the head is overriding my changes. The button itself is created by another script which als ...

Tips for employing the slice approach in a data-table utilizing Vue

I have a unique situation in my Vue app where I'm utilizing v-data table. The current display of data in the table works fine, but I now want to enhance it by incorporating the slice method. Here is the current data displayed in the table: https://i ...

Tooltip not displaying value on Google Line Chart when hovered over

Utilizing the Google Line Charts within Angular2 and TypeScript, I encountered an issue. While the line chart appeared visually appealing, the tool-tip did not display the exact values when hovered over a point on the chart. I'm puzzled as to why the ...