0

A bit of a background, I am beginner level programmer and I tried making a website that collects the amount of your average daily spending and finds your yearly and monthly spending but for the collecting the amount of money part, I wanted to put class for the but when I tried getElementsByClass, it didn't work while getElementById completely did. Is there a reason why? The code for my program is;

<!DOCTYPE html>
<html>
    <head>
        <title>SpendCalculator</title>
        <script src="SC.js"></script>
        <link href="SC.css" rel="stylesheet">
    </head>
    <body>

        <input id="input" type="text" placeholder="Money for breakfast">
        <button class="submit" onclick="add()">Submit</button>
        <h1 id="total"></h1>
    </body>
</html>

HTML

let total = 0;

function add() {
    console.log(document.getElementById("input").value)
    total += document.getElementsByClassName("input").value
    console.log(total)
    document.getElementById("total").innerHTML = total + "$!";
}

JS

Parisamil
  • 23
  • 5
  • 1
    `getElementsByClassName` returns an array like object of elements, so you need to put `[0]` to access it. – TechySharnav Jul 09 '22 at 09:36
  • There is no element with `class='input'` in your html ... And even if there was, like @TechySharnav said, the result of `getElementsByClassName` is (as the name suggests) a collection... – derpirscher Jul 09 '22 at 09:38
  • Food for thought: “get” + any plural noun should always return a collection in any well designed API – danronmoon Jul 09 '22 at 09:47

0 Answers0