Set CSS Property in JavaScript

Set CSS property in JavaScript?

Use element.style:

var element = document.createElement('select');
element.style.width = "100px";

How to add CSS properties with JavaScript without style attributes

You can create a style element in DOM and append anything to it which will automatically apply to your element

const appendStyle = (customStyles) => {
const styleEl = document.createElement('style');
styleEl.innterHTML = `yourTagName {${customStyles}}`;
document.body.appendChild(styleEl);
}

appendStyle('background-color: red; font-size: 15');

Change CSS with properties defined in an object

const btn = document.getElementById('btn');const box = document.getElementById('b');
const myobj = { 'width': '200px', 'background': 'yellow'};
btn.addEventListener('click', () => { for (let [key, val] of Object.entries(myobj)) { box.style[key] = val; }});
.box {  width: 300px;  height: 300px;  background: grey;}
<div class="box" id="b"></div><button id="btn">click</button>

How can one set a CSS property with the !important flag via the DOM?

Here you go:

myElement.style.setProperty( 'property', 'newValue', 'important' );

Live demo: http://jsfiddle.net/mJHEf/

Getting or changing CSS class property with Javascript using DOM style

As mentioned by Quynh Nguyen, you don't need the '.' in the className. However - document.getElementsByClassName('col1') will return an array of objects.

This will return an "undefined" value because an array doesn't have a class. You'll still need to loop through the array elements...

function changeBGColor() {
var cols = document.getElementsByClassName('col1');
for(i = 0; i < cols.length; i++) {
cols[i].style.backgroundColor = 'blue';
}
}


Related Topics



Leave a reply



Submit