I am currently facing an issue where I receive the error message: Uncaught TypeError: Cannot read properties of undefined (reading 'add') when trying to add a class to a div using a button.
After researching on Stack Overflow, I stumbled upon a thread with a similar problem. Here is my simplified code:
<!DOCTYPE html>
<html lang="en">
<body>
<div class="name-row">Hello!</div>
<button type="button" onclick="clear()" id="clearButton">Clear</button>
<script>
document.getElementById('clearButton').addEventListener('click', function () {
let allNamesElm = document.getElementsByClassName("name-row");
allNamesElm.classList.add("showing");
window.alert("Cleared!");
console.log("cleared");
});
</script>
</body>
</html>
Despite attempting to explicitly call the function, the code does not execute as expected:
<!DOCTYPE html>
<html lang="en">
<body>
<div class="name-row">Hello!</div>
<button type="button" onclick="clear()" id="clearButton">Clear</button>
<script>
function clear() {
let allNamesElm = document.getElementsByClassName("name-row");
allNamesElm.classList.add("showing");
window.alert("Cleared!");
console.log("cleared");
};
</script>
</body>
</html>
It seems like a simple mistake, but despite my efforts to correct it, the issue persists. Any help would be greatly appreciated!