JS: adding styles to a div through object.value results in nothing

104
February 11, 2022, at 4:50 PM
let styles1 = {
    margin1: '50px',
    borderRadius1: '20px',
    borderStyle1: 'solid',
    borderWidth1: '10px',
    borderColor1: '#81ecec'
}
let elem = document.createElement('div');
elem.style.margin = styles1.margin1.value + 'px';
elem.style.borderRadius = styles1.borderRadius1.value + 'px';
elem.style.borderStyle = styles1.borderStyle1.value;
elem.style.borderWidth = styles1.borderWidth1.value + 'px';
elem.style.borderColor = styles1.borderColor1.value;
document.body.appendChild(elem);

The other part of the code(not mentioned) works perfectly, but for some reason none of the border styles work(and without any errors?). Anyone got any ideas?

Answer 1

There are some things going wrong in your code. When you reference a key in an object like styles1.margin1 it already returns "50px". So there is no need to add a .value. Meaning that you do not need to append a "px" at the end of each style assignment. This should do the trick:

let elem = document.createElement('div');
elem.style.margin = styles1.margin1;
elem.style.borderRadius = styles1.borderRadius1;
elem.style.borderStyle = styles1.borderStyle1;
elem.style.borderWidth = styles1.borderWidth1;
elem.style.borderColor = styles1.borderColor1;
document.body.appendChild(elem);
Rent Charter Buses Company
READ ALSO
Vue3 prop updates title attribute but not computed prop

Vue3 prop updates title attribute but not computed prop

I'm using an external library rendered using Vue3It has the following component from a third part library [Edit: I realize the GitHub repo for that library is out of date, so updating with the actual code in my node_modules

103
Wordpress full page with animated borders effect

Wordpress full page with animated borders effect

Anybody knows a way to archive the following effect? I want to have a page with layout like picture 1jpg (and with a menu in top) full page with borders in different colors, moving, and on mouseover/hoover the border changes, like in picture 2

92
How to make noWrap work with Breadcrumbs?

How to make noWrap work with Breadcrumbs?

I'm trying to make the MUI component Breadcrumbs responsive:

105
How can I set multiple CSS styles in JavaScript?

How can I set multiple CSS styles in JavaScript?

I have the following JavaScript variables:

144