Pavel K.
Pavel K.

Reputation: 1

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

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?

Upvotes: 0

Views: 22

Answers (1)

Palladium02
Palladium02

Reputation: 1171

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);

Upvotes: 2

Related Questions