Ask Your Question
2

What is the method to modify the CSS of a specific element using javascript?

asked 2022-12-18 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-10-30 01:00:00 +0000

nofretete gravatar image

There are multiple methods to modify the CSS of a specific element using javascript. Here are a few of them:

  1. Using the style property of the element:
// 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';
  1. Using the setAttribute method:
// 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;');
  1. Using the classList property:
// 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; }
  1. Using the CSSStyleSheet object:
// 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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-12-18 11:00:00 +0000

Seen: 11 times

Last updated: Oct 30 '22