Working with Hierarchical Node Properties - Exercise

Contact Us or call 1-877-932-8228
Working with Hierarchical Node Properties - Exercise

Working with Hierarchical Node Properties

Duration: 10 to 15 minutes.

In this exercise, you will practice working with JavaScript's hierarchical node properties.

  1. Open EventHandlers/Exercises/elementNodes.html for editing.
  2. Note that a click handler has been added to the button so that the function setFontSize() is called when the user clicks the button.
  3. Write the body of function setFontSize() to set the size of the font for each list item to be successively greater, with the first list item having font size 10px, the second 12px, etc.

Solution:

EventHandlers/Solutions/elementNodes.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Element Nodes</title>
<link href="style.css" rel="stylesheet">
<script>
	function setFontSize() {
		var list = document.querySelector("ul");
		var childFirst = list.firstChild;
		childFirst.style.fontSize = "10px";
		var nextSib = childFirst.nextSibling;
		nextSib.style.fontSize = "12px";
		nextSib = nextSib.nextSibling;
		nextSib.style.fontSize = "14px";
		nextSib = nextSib.nextSibling;
		nextSib.style.fontSize = "16px";
		nextSib = nextSib.nextSibling;
		nextSib.style.fontSize = "18px";
		nextSib = nextSib.nextSibling;
		nextSib.style.fontSize = "20px";
		nextSib = nextSib.nextSibling;
		nextSib.style.fontSize = "22px";
		nextSib = nextSib.nextSibling;
		nextSib.style.fontSize = "24px";
		nextSib = nextSib.nextSibling;
		nextSib.style.fontSize = "26px";
		nextSib = nextSib.nextSibling;
		nextSib.style.fontSize = "28px";
	}
</script>
</head>
<body>
	<button onclick="setFontSize()" type="button">Go</button>
	<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li><li>Item 4</li><li>Item 5</li><li>Item 6</li><li>Item 7</li><li>Item 8</li><li>Item 9</li><li>Item 10</li></ul>
</body>
</html>

Code Explanation

In function setFontSize() we use document.querySelector("ul") to get the unordered list, firstChild to get the first list item, and nextSibling to get each next item. Of course, if we were to use a loop (at which we'll look later in the course) we could have written much more economical code.

Next