1.

How can you style elements using JavaScript?

Answer»

There are multiple ways to dynamically add styles to HTML elements using JavaScript. The most DIRECT way to add style using JavaScript is using the style PROPERTY on elements that can be accessed in JavaScript using the DOM API. There are multiple document methods like getElementById(), getElementsByClassName(), getElementsByTagName() and querySelector() that allow fetching HTML Element OBJECTS whose CSS selectors match the specified string. Once you have the HTML element, you can access the style property and apply the desired style VALUE.

For example,

const element = document.getElementById(‘header’); element.style.color = ‘black’; // change the color element.style.fontSize = ‘1rem’; // change the font size

The general SYNTAX of applying style is element.style.cssProperty = value. Here, the CSS property names are written in camelCase.  

A cleaner way to dynamically change the styles of an element using JavaScript is to add or remove the classes from the element.

Example,

const element = document.getElementById(‘header’); element.classList.add(‘className’); element.classList.remove(‘className’);

By adding or removing className to the list of classes of the element, the styles can be dynamically added or removed.



Discussion

No Comment Found