Coming from Lesson 6: Mad Libs Game - Interactive? Excellent! Now youโll learn how to replace helper functions with native JavaScript DOM methods.
document.getElementById(), addEventListener(), and other native APIsTake your Lesson 5 (Water Conservation App) or Lesson 6 (Mad Libs Game) project and refactor it to use native JavaScript instead of helper functions.
Youโll create a new branch called native-dom-functions and rewrite your JavaScript code to use the browserโs built-in DOM methods directly.
Before starting this lesson, youโll create a new branch to safely experiment with your code:
Open your terminal and navigate to your project folder, then:
# Create the new branch
git branch native-dom-functions
# Switch to the new branch
git switch native-dom-functions
git branch
You should see * native-dom-functions with an asterisk indicating your current branch.
First, letโs examine how the helper functions work by looking at helpers.js:
onEvent(id, event, handler)function onEvent(id, event, handler) {
var el = document.getElementById(id); // โ Native method!
if (!el) {
console.warn("onEvent: Element with id '" + id + "' not found.");
return;
}
el.addEventListener(event, handler); // โ Native method!
console.info("onEvent: Listening for '" + event + "' on #" + id);
}
What it does:
document.getElementById()addEventListener()Native replacement:
// Instead of: onEvent("myButton", "click", handleClick)
const element = document.getElementById("myButton");
if (element) {
element.addEventListener("click", handleClick);
}
setProperty(id, property, value)function setProperty(id, property, value) {
var el = document.getElementById(id); // โ Native method!
if (!el) {
console.warn("setProperty: Element with id '" + id + "' not found.");
return;
}
el.style[property] = value; // โ Native method!
console.info("setProperty: #" + id + " โ " + property + " = " + value);
}
Native replacement:
// Instead of: setProperty("myDiv", "color", "blue")
const element = document.getElementById("myDiv");
if (element) {
element.style.color = "blue";
}
setText(id, text)function setText(id, text) {
var el = document.getElementById(id); // โ Native method!
if (!el) {
console.warn("setText: Element with id '" + id + "' not found.");
return;
}
el.textContent = text; // โ Native method!
console.info("setText: #" + id + " โ \"" + text + "\"");
}
Native replacement:
// Instead of: setText("myLabel", "Hello World!")
const element = document.getElementById("myLabel");
if (element) {
element.textContent = "Hello World!";
}
Remove this line from your HTML:
<!-- Remove this: -->
<script src="helpers.js"></script>
onEvent("languageBtn", "click", toggleLanguage);
setProperty("bottleChoice", "backgroundColor", "green");
setText("message", "Great choice!");
playSound("success.mp3");
// Event handling
const languageBtn = document.getElementById("languageBtn");
if (languageBtn) {
languageBtn.addEventListener("click", toggleLanguage);
}
// Property setting
const bottleChoice = document.getElementById("bottleChoice");
if (bottleChoice) {
bottleChoice.style.backgroundColor = "green";
}
// Text setting
const message = document.getElementById("message");
if (message) {
message.textContent = "Great choice!";
}
// Sound playing
const audio = new Audio("success.mp3");
audio.play();
// Get element by ID
const element = document.getElementById("myId");
// Get element by CSS selector
const element = document.querySelector(".myClass");
const elements = document.querySelectorAll(".myClass");
// Add event listener
element.addEventListener("click", function() {
console.log("Clicked!");
});
// Remove event listener
element.removeEventListener("click", handlerFunction);
// Text content
element.textContent = "New text";
// HTML content
element.innerHTML = "<strong>Bold text</strong>";
// Input values
inputElement.value = "New value";
// Individual properties
element.style.color = "red";
element.style.backgroundColor = "blue";
// Multiple properties
element.style.cssText = "color: red; background-color: blue;";
// CSS classes
element.classList.add("highlight");
element.classList.remove("highlight");
element.classList.toggle("highlight");
// Create and play audio
const audio = new Audio("sound.mp3");
audio.play();
audio.pause();
audio.loop = true;
Always check if elements exist before using them:
const element = document.getElementById("myId");
if (element) {
// Safe to use element
element.addEventListener("click", handler);
} else {
console.error("Element 'myId' not found");
}
Group related functionality:
// Element references
const elements = {
languageBtn: document.getElementById("languageBtn"),
message: document.getElementById("message"),
bottleChoice: document.getElementById("bottleChoice")
};
// Event handlers
function initializeEvents() {
if (elements.languageBtn) {
elements.languageBtn.addEventListener("click", toggleLanguage);
}
}
getElementById repeatedlyAfter completing this lesson:
Youโve successfully learned:
โ
How helper functions work internally
โ
Native JavaScript DOM methods
โ
Element selection and manipulation
โ
Event handling without external libraries
โ
Code refactoring techniques
โ
Branch management with Git
Youโre now ready to work with vanilla JavaScript! ๐
Enhance your refactored project with additional native DOM features:
element.animate() for smooth transitionsdatasetlocalStorageThis challenge will help you master advanced DOM manipulation techniques!