Apply CSS Dynamically with JavaScript

Apply CSS dynamically with JavaScript

Using Jquery

Use the css() function to apply style to existing elements where you pass an object containing styles :

var styles = {
backgroundColor : "#ddd",
fontWeight: ""
};
$("#myId").css(styles);

You can also apply one style at the time with :

$("#myId").css("border-color", "#FFFFFF");

Vanilla JS :

var myDiv = document.getElementById("#myId");
myDiv.setAttribute("style", "border-color:#FFFFFF;");

With Css :

You can also use a separate css file containing the different styles needed inside classes, and depending on the context you add or remove those classes to your elements.

in your css file you can have classes like

.myClass {
background-color: red;
}

.myOtherClass {
background-color: blue;
}

Again using jquery, to add or remove a class to an element, you can use

$("#myDiv").addClass('myClass');

or

$("#myDiv").removeClass('myClass');

Again, you can also do the same with vanilla JS:

document.getElementById("#myId").classList.add('myClass') 

or

document.getElementById("#myId").classList.remove('myClass') 

I think this is a cleaner way as it separates your style from your logic. But if the values of your css depends from what is returned by the server, this solution might be difficult to apply.

How to dynamically create CSS class in JavaScript and apply?

Here is an option:

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { color: #f00; }';
document.getElementsByTagName('head')[0].appendChild(style);

document.getElementById('someElementId').className = 'cssClass';
<div id="someElementId">test text</div>

Dynamically change CSS rules in JavaScript or jQuery

You jQuery .css() method to do that.

$('.red').css('color', 'purple');

For multiple rules:

$('.red').css({
'color': 'purple',
'font-size': '20px'
});

When you add dynamic element in future to DOM by the way of append, just give those element some class or id and write CSS rules like above after appending them and they will applied for all dynamically created element.

Working sample

Note

Add dynamic rules is not a good solution in my point of view. Instead of the you can load some external CSS file.

But if you need something like dynamic rules add method then:

$('head').append(
$('<style/>', {
id: 'mystyle',
html: '.red {color: purple }'
})
);

And for future use:

$('#mystyle').append(' .someother { color: green; font-size: 13px } ');

Working sample

apply CSS style to particular elements dynamically

Without using classes:

/* using CSS */
div p {
color: #ff0000;
}

// using jQuery
$("div p").css({
color : "#ff0000"
});

With classes for <p> elements:

<!-- HTML -->
<div>
<p class="mypar">...</p>
<p class="mypar">...</p>
</div>

/* using CSS */
div p.mypar {
color: #ff0000;
}

// using jQuery
$("div p.mypar").css({
color : "#ff0000"
});

With classes for <div> element:

<!-- HTML -->
<div class="mydiv">
<p>...</p>
<p>...</p>
</div>

/* using CSS */
div.mydiv p {
color: #ff0000;
}

// using jQuery
$("div.mydiv p").css({
color : "#ff0000"
});

Add CSS style and media queries to dynamically generated HTML table with JavaScript

I was trying to create a simple responsive table in CSS. The example code I found required the header labels to be hardcoded on the <td></td> tags. But I wanted a way to dynamically label the <td></td> tags with the table headers content when the window resizes.

Since I am new to CSS and JS, I had no idea of accessing the content attribute of an HTML element. @Immaculata's answer gave me a hint.

See working code below.

CSS: defined within the @media screen and (max-width: 600px)

table td::before {
content: attr(data-label);
float: left;
font-weight: bold;
text-transform: uppercase;
}

HTML and JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://unpkg.com/read-excel-file@4.x/bundle/read-excel-file.min.js"></script>
<link href="style.css" rel="stylesheet" />
<title>Document</title>
</head>
<body>
<input type="file" id="input" />
<table>
<caption>
Table Title
</caption>
</table>
<script>

var input = document.getElementById("input");
input.addEventListener("change", function () {

//Code to populate the HTML table goes here...

});

const mediaQuery = window.matchMedia("(max-width: 600px)");
mediaQuery.addListener(onWindowChanged);

function onWindowChanged(e) {
if (e.matches) {
const dataTable = document.querySelector("table");
const thElements = dataTable.querySelectorAll("thead th");
const tdLabels = Array.from(thElements).map((element) => element.innerText);
dataTable.querySelectorAll("tbody tr").forEach((tr) => {
Array.from(tr.children).forEach((td, index) =>
td.setAttribute("data-label", tdLabels[index])
);
});
}
}

</script>
</body>
</html>

How to add CSS to a dynamic table created with javascript

Made you a snippet of your code to show you that it works. Mayhap you have contradictions in your actual stylesheet.

Be aware to place the body tag at the correct hierarchy.

function addTable() {

let colonne = Math.floor(Math.random() * 5)+2;
let righe = Math.floor(Math.random() * 5)+2;

var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();

today = mm + '/' + dd + '/' + yyyy;

let providers = ["p1", "p2", "p3", "np4", "p5"];
let testcases = ["tc1", "tc2", "tc3", "tc4", "tc5"];


var myTableDiv = document.getElementById("myDynamicTable");

var table = document.createElement('table');
table.classList.add('tablestyle');

var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);



for (var i=0; i<righe; i++){
var tr = document.createElement('tr');
tr.style.backgroundColor = 'red';
tableBody.appendChild(tr);

for (var j=0; j<colonne; j++){
var td = document.createElement('td');
td.width='75';

if(i==0){
if(j==0){ //prima casella
addCell(td, tr, today);
}
else { //prima riga
addCell(td, tr, providers[j-1]);
}
}
else {
if(j==0){ //prima colonna
addCell(td, tr, testcases[i-1]);
}
else {
addCell(td, tr, Math.floor(Math.random() * 50));
}

}


}
}
myTableDiv.appendChild(table);

}

function addCell(td, tr, valoreCella){
td.appendChild(document.createTextNode(valoreCella));
tr.appendChild(td);
}
.tablestyle{
font-weight: bold;
color: green
}
<body onload="addTable()">
<div class="block">
<h1>STORICO DEI DATI</h1>
<div id="myDynamicTable" class="table">
<!--JS-->
</div>
</div>
</body>

Generate dynamic css based on variables angular

Direct approach available in angular is using ngstyle as follows

<div [ngStyle]="{'color': style.colorVal ? style.colorVal : '#000', 'font-size' : style.fontSize ? style.fontSize : '16px' }"></div>

After going through different methods and approached to add dynamic css to all pages on angular app I ended up with following solutions.

Requirement : generate dynamic css based on values returned from and API to change design and styling.

Solution :

  1. create a new component and create a service to load dynamic css variables from API.
  2. Add style tag in template file and use variable values for properties.
  3. Load this template on all pages or on main template.
  4. On app build style will be moved to head tag.

Code sample

import { CssService} from './Css.service';

@Component({
selector: 'DynamicCss',
templateUrl: './DynamicCss.component.html',
styleUrls: ['./DynamicCss.component.scss']
})
export class ServiceProviderComponent implements OnInit {
cssVariables: any;
constructor(private cssService:CssService){
/* call the service/api to get the css variable values in cssVariables */

}
}

Now apply css using jquery or javascript to append css with help of function like following

appendCss(customData)
{
let text = '.custom-form-1 {
background-image: url("`+customData.background_image+`");
}';
$(document).ready(function(){
$("style").append(text);
});
}

and call this function after loading custom data from service or other variable like I did it ngOnInit

ngOnInit(){
this.appendCss(this.customizeFormData);
}

Its using jquery but can be done with javascript/typescript as well if you dont want to use jquery in your angular app

Other useful resource https://github.com/angular/angular/issues/9343#issuecomment-312035896



Related Topics



Leave a reply



Submit