By the end of this lesson, you will know how to build a simple grade calculator for students using the DOM.
The DOM stands for Document Object Model. It is a method that allows JavaScript to access and modify elements on web pages. For instance, if you want to change the color of text on a webpage, you utilize the DOM. This concept is similar to how we can alter items on a shopping list!
File: grade_calculator.html
<!DOCTYPE html>
<html>
<head>
<title>Grade Calculator</title>
<script src="script.js" defer></script>
</head>
<body>
<h1>Student Grade Calculator</h1>
<label for="name">Name:</label>
<input type="text" id="name">
<label for="grade">Grade:</label>
<input type="number" id="grade">
<button id="submit">Submit</button>
<ul id="gradeList"></ul>
</body>
</html>
Expected Output:
If you enter "John" as the name and "85" as the grade, it will show:
- John: 85
In the code above, we begin with HTML to construct a straightforward form. The form includes inputs for the name and grade, allowing users to enter their details. The button in this form has an ID of “submit,” which we will leverage in our JavaScript for added functionality. Additionally, the list with the ID of “gradeList” is where we will present the entered grades. Therefore, ensuring that each component functions correctly is essential.
Your challenge is to develop a JavaScript file named script.js that incorporates the following functionalities:
script.js file is correctly linked to the HTML file.const submitButton = document.getElementById('submit');
const gradeList = document.getElementById('gradeList');
submitButton.addEventListener('click', function() {
const nameInput = document.getElementById('name').value;
const gradeInput = document.getElementById('grade').value;
const listItem = document.createElement('li');
listItem.textContent = nameInput + ': ' + gradeInput;
gradeList.appendChild(listItem);
document.getElementById('name').value = '';
document.getElementById('grade').value = '';
});
To further enhance your JavaScript skills, consider checking out the lesson on examples of JavaScript in use. Additionally, grasping how HTML, CSS, and JavaScript work together can also deepen your understanding.