Working with querySelector() - Exercise

Contact Us or call 1-877-932-8228
Working with querySelector() - Exercise

Working with querySelector()

Duration: 10 to 15 minutes.

In this exercise, you will practice working with JavaScript's querySelector() function.

  1. Open EventHandlers/Exercises/query-selector.html for editing.
  2. Add a click handler to the button so that the function setColor() is called when the user clicks the button.
  3. Write the contents of function setColor() to do the following:
    • Use prompt() to get from the user the element he/she wishes to color - expected input would be a tag (like p), a class (like .a), or an id (like #x).
    • Use prompt() to get from the user their desired color (like blue or red).
    • Use querySelector() to get the user's desired element, then set the color of that element.

Solution:

EventHandlers/Solutions/query-selector.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>querySelector()</title>
<link href="style.css" rel="stylesheet">
<script>
	function setColor() {
		var userElement = prompt("Element to color?", "");
		var userColor = prompt("What color?", "");
		document.querySelector(userElement).style.backgroundColor = userColor;
	}
</script>
</head>
<body>
	<button onclick="setColor();" type="button">Go</button>
	<ul>
		<li>Item 1</li>
		<li class="a">Item 2 | class "a"</li>
		<li>Item 3</li>
		<li class="b">Item 4 | class "b"</li>
		<li>Item 5</li>
		<li class="c">Item 6 | class "c"</li>
		<li>Item 7</li>
		<li id="x">Item 8 | id "x"</li>
		<li class="a">Item 9 | class "a"</li>
		<li>Item 10</li>
	</ul>
</body>
</html>

Code Explanation

We add onclick="setColor();" as an attribute to the button at the top of the page so that function setColor() is called when the user clicks the button.

We use prompt() to get from the user the desired element (storing it in variable userElement) and the desired color (storing it in userColor).

Lastly, we use the code

document.querySelector(userElement).style.backgroundColor = userColor;

to set the color of the first matched element supplied by the user:

  • If the user entered "ul" and "green", the entire unordered list would be colored green.
  • If the user entered "li" and "red", the first bullet would be colored red.
  • If the user entered ".b" and "blue", the fourth bullet would be colored blue.
  • If the user entered "#x" and "orange", the eigth bullet would be colored orange.
  • If the user entered ".w" and "red", nothing would happen, as there is no element with class "w". (Actually an error would occur, as the returned value of document.querySelector() would be null.)
Next