JavaScript Cheet Sheet

2.2 - HTML Objects

In the following example, the p elements will change when the button is clicked. The code is shown at the bottom of the page.

Paragraph One

Paragraph Two

Paragraph Three

Paragraph Four

Paragraph Five

// store p elements in variable paragraphs
let paragraphs = document.body.getElementsByTagName("p");

// initialize number to 1. This will be used to make a decision.
let number = 1;

// When the function is called, the 5th paragraph is moved to the first position
function getPargraph(){

// increment number each time the function is called
number++;

document.body.insertBefore(paragraphs[4], paragraphs[0]);
// If number divided by 2 has zero remained, myHeading ID color will be red. Otherwise it will be black. This is done using style.color to affect the styling.
if(number%2 == 0)
   myHeading.style.color = "red";
else
   myHeading.style.color = "black";
}