There are multiple methods to modify the CSS of a specific element using javascript. Here are a few of them:
// Get the element using document.getElementById or any other method
const element = document.getElementById('my-element-id');
// Modify the CSS of the element using the style property
element.style.backgroundColor = 'red';
element.style.fontSize = '16px';
// Get the element using document.getElementById or any other method
const element = document.getElementById('my-element-id');
// Modify the CSS of the element using the setAttribute method
element.setAttribute('style', 'background-color: red; font-size: 16px;');
// Get the element using document.getElementById or any other method
const element = document.getElementById('my-element-id');
// Add a class to the element using the classList property
element.classList.add('my-class');
// Modify the CSS of the element using the added class in CSS file
// For Example: .my-class { background-color: red; font-size: 16px; }
// Get the stylesheet of the document
const styleSheet = document.styleSheets[0];
// Modify the CSS of the specific element in the stylesheet
styleSheet.addRule('#my-element-id', 'background-color: red; font-size: 16px;');
Note: The above methods are just a few examples, there are many other ways to modify the CSS using javascript.
Asked: 2022-12-18 11:00:00 +0000
Seen: 11 times
Last updated: Oct 30 '22