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
Intercept a Form Submit in JavaScript and Prevent Normal Submission
Changing Element Style Attribute Dynamically Using JavaScript
How to Connect HTML Divs With Lines
How to Parse HTML in Google Apps Script
Get Caret Position in HTML Input
Angularjs to Output Plain Text Instead of Html
How to Get Background Image Url of an Element Using JavaScript
Equivalent of Jquery .Hide() to Set Visibility: Hidden
Force Link to Open in Mobile Safari from a Web App With JavaScript
What Is the Explicit Promise Construction Antipattern and How to Avoid It
Prototypical Inheritance - Writing Up
JavaScript Infamous Loop Issue