Is there any way I could style my element more economically and avoid writing so many lines for style? If I continue styling, it will be super long. Maybe import CSS from a css file?
function addClass() {
console.log('fired');
let container = document.createElement('div');
container.setAttribute('class', 'container');
container.style.width= "100px";
container.style.height= "100px";
container.style.border= "1px solid grey";
document.body.appendChild(container);
Yes, define a class named “container” in CSS with the properties you want to style and then add the class to the element via JS.
Predefined CSS
.container {
width: 100px;
height: 100px;
border: 1px solid grey;
}
JS
function addClass() {
let container = document.createElement('div');
container.setAttribute('class', 'container');
document.body.appendChild(container);
}
Another option instead of the setAttribute method is to add the class to the classList.
container.classList.add('container');
They both accomplish the same thing.
Yes, that’s right. Predefined CSS works also for classes added in JS. Thanks for the clarification.