Start with this HTML page:
<body>
<p>Lorem ipsum.</p>
<p id="p1">In eu blandit velit.</p>
<p>Proin turpis erat, porta dignissim dapibus
in, rhoncus et diam. Sed id ante mattis.</p>
<p class="flagged">Suspendisse.</p>
<p class="flagged">Class aptent taciti sociosqu ad litora
torquent per conubia nostra, per inceptos
himenaeos. Fusce sed nunc nisi.</p>
<button>Perform Ex2</button>
</body>
Write JavaScript code that does each of the following when the "Perform Ex2"
button is clicked:
- Change the text color of the paragraph with id #p1 to blue.
- Change the text of the paragraphs that implement the class
.flagged to uppercase.
- Count the total number of paragraphs.
Answer:
=================================================
<!DOCTYPE html>
<!-- HTML File: index.html -->
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ex 2</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
</head>
<body>
<h1>ex 2</h1>
<p>Lorem ipsum.</p>
<p id="p1">In eu blandit velit.</p>
<p>Proin turpis erat, porta dignissim dapibus
in, rhoncus et diam. Sed id ante mattis.</p>
<p class="flagged">Suspendisse.</p>
<p class="flagged">Class aptent taciti sociosqu ad litora
torquent per conubia nostra, per inceptos
himenaeos. Fusce sed nunc nisi.</p>
<button>Perform Ex2</button>
</body>
</html>
-------------------------------------------------
/* Stylesheet: styles.css */
body { font-family: verdana; }
.flagged { font-style: italic; }
-------------------------------------------------
// JavaScript script: script.js
// Exercise 5a.
function changeToBlue( ) {
var p1Obj = document.querySelector("#p1");
p1Obj.style.color = "blue";
}
// Exercise 5b.
function changeToUpperCase( ) {
var parObjects = document.querySelectorAll(".flagged");
for(p of parObjects) {
var str = p.innerHTML;
p.innerHTML = str.toUpperCase( );
}
}
// Exercise 5c.
function showCount( ) {
var paras = document.querySelectorAll("p");
var count = paras.length;
var newP = document.createElement("p");
var bodyObj = document.querySelector("body");
bodyObj.appendChild(newP);
newP.innerHTML = "Paragraph count: " + count;
}
// Execute code for Ex. 5a, 5b, and 5c.
function buttonListener( ) {
changeToBlue( );
changeToUpperCase( );
showCount( );
}
// Attach click event listener to button.
function init( ) {
var button1 = document.querySelector("button");
button1.addEventListener("click", buttonListener);
}
// The following line is an alternative to window.onload:
document.addEventListener("DOMContentLoaded", init);
=================================================