style css js code example
Example 1: add style javascript
// Bad:
element.setAttribute("style", "background-color: red;");
// Good:
element.style.backgroundColor = "red";
Example 2: html css javascript
For example:
<div id="me">Click me!</div>
<style>
div {
height: 128px;
width: 128px;
background: red;
}
</style>
<script>
document.getElementById("me".addEventListener("click", function(){
document.getElementById("me").style.background = 'blue';
});
</script>
Example 3: javascript css
document.getElementById(id).style.property = new style
Example 4: js add css style to element
// Create our stylesheet
var style = document.createElement('style');
style.innerHTML =
'.some-element {' +
'color: purple;' +
'background-color: #e5e5e5;' +
'height: 150px;' +
'}';
// Get the first script tag
var ref = document.querySelector('script');
// Insert our new styles before the first script tag
ref.parentNode.insertBefore(style, ref);
Example 5: css in js
JSS is an authoring tool for CSS which allows you to use JavaScript to describe styles in a declarative, conflict-free and reusable way. It can compile in the browser, server-side or at build time in Node.
JSS is framework agnostic. It consists of multiple packages: the core, plugins, framework integrations and others.
Example 6: change style js
// select element from DOM
const el = document.querySelector('.para')
// change css style
el.style.color = 'purple'