Modify CSS Using JavaScript

JavaScript can be used to change the style of elements within a webpage, similarly to how CSS can be used. However, the difference is JavaScript can be used to dynamically change the style the element at runtime, meaning while the user to viewing is looking at the page or in reaction to an event like a button click. CSS can be used to change the style of elements dynamically too but not too the same extent as JavaScript.

Firstly you need an element to modify. Below is a basic div in html with the id of ‘myDiv’, which will allow us to grab the element using JavaScript, and there is some text within the div.

Within JavaScript you can then grab the element using the ‘getElementById’ method of the document object and passing in the name of the id of the element you want to grab. The ‘style’ object is used to change the look of an element, every element has a ‘style’ object inside. You then add the name of the attribute you want to change and set the value. The name of the properties will look similar to the names within CSS because they’re the same name, but they use camel case rather than hyphens. The colouring works the same as CSS too, you can use hexadecimal colours, rgb colours, or just predefined names.

There are many different style attributes that can be changed of an element using JavaScript, the above code only shows three. Using JavaScript to change the style of an element can give you more flexibility and dynamic webpages. You could use this to change an element’s position, colour, shape, etc based on user interaction, such as clicking, scrolling, keyboard presses, etc.

One thought to “Modify CSS Using JavaScript”

Leave a Reply