Lessons 137 & 138 – Complete 2020 Web Development Bootcamp

Lesson 137 – Manipulating and Changing Styles of HTML Elements with Javascript

All CSS properties can be changed using Javascript.

The names of the CSS properties may look a bit different in Javascript. Javascript used camel casing.

In CSS the font size property is written “font-size” but in Javascript it is written “fontSize”.

This page on W3Schools sets out the various CSS properties as they are written in Javascript along with a description of what they do.

When you use Javascript to change CSS values, then the value that you set the CSS property to, has to be represented as a string. For example, the value of text-decoration that is being assigned to the CSS id of heading has to be represented as the string “line-through” –

document.getElementById("heading").style.textDecoration = "line-through";

The challenge in this lesson was to use Javascript to change the background color of a button to yellow. This is my solution –

document.querySelector(".btn").style.backgroundColor = "yellow";

Lesson 138 – The Separation of Concerns: Structure vs. Style vs. Behaviour

The separation of concerns means that:

  • HTML is for content only;
  • CSS is for styling;
  • Javascript is for behaviour.

In Javascript, you can use “classList” to find out what classes are applied to a particular element. So, for example, if you want to find out what classes are applied to a button element, you can use –

document.querySelector("button").classList;

You can then add additional classes to the element using –

document.querySelector("button").classList.add("invisible");

The result is that the element button will now have two CSS classes – “btn” and “invisible”.

In your CSS file, you will have the styling that is applied to the “invisible” class. For example,

.invisible {
 visibility: hidden;
}

This way you can keep your CSS styles within your stylesheet but use Javascript to turn them on and off.

You can also use Javascript to remove a class from an element. For example,

document.querySelector("button").classList.remove("invisible");

You can also use “toggle” to add a class if it is not applied or to remove it if it is already applied. This is an example of the “toggle” syntax –

document.querySelector("button").classList.toggle("invisible");

The challenge in this lesson was to use Javascript to add a class to an h1 element and change its color and font size.

This is the “huge” class I created in the stylesheet –

.huge {
	font-size: 10rem;
	font-weight: bold;
	color: green;
}

This is the Javascript code I inserted in the index.js file –

document.querySelector("h1").classList.add("huge");