Setting CSS from the DOM:

Up to now, this site has been setting inline CSS in its functions. For example, when we have changed the color of text, we have used:

we can of course use this for any standard attribute. We can change an <img> source, or URL link, or the styling of a text box...

We can see that we set the src key of the <img> tag, which when the page was loaded was not defined. Then, our code styled the border using inline CSS within the JavaScript code.

Incidentally, we also used callback functions within each block of code to call the function explain(), which shows the code.


But there is a better way than using inline CSS:


classList.add() / classList.remove()

The <body> element of this page has been assigned both an id and a class:

class="light"

id="changeTheme"

The Javascript has a self-declaring function that changes the theme from .light to .dark depending on the time. If you are reading this after 7 pm, the background color of this page will be set to black, while the text color will be set to white. It does this by calling either function light() or dark().

These functions, light() or dark() call on the id of the <body> element, and then either add or remove (that is, change) the class the element is accorded in the CSS: