+ 2

I'm trying to build a calculator...but when I use getElementsByClassName instead of getElementById it does not work as the same

Either Id or class both are used to select the element. But why class or queryselector does not in this case <Input class="calc" Id ="output"> <button onclick= "display(0)"></button> .... .... ... Javascript //This is not working ..................................... Let a = document.getElementsByClassName("calc"); Function display(num){ a.value += num; } // This is working .............................. Let a = document.getElementById("output"); Function display(num){ a.value += num; }

22nd Dec 2022, 8:14 AM
YOGESHWARAN
YOGESHWARAN - avatar
3 Respuestas
+ 7
The getElementsByClassName returns an array of elements. While getElementById returns single element. So in first case, treat a as array as a[0].value += num;
22nd Dec 2022, 8:25 AM
Jayakrishna 🇮🇳
+ 4
ID is (should be) unique but there can be multiple elements in the HTML document that have the same class. Therefore, getElementsByClassName will give you a list that can have multiple elements. So use it like this to get the first one: getElementsByClassName("calc")[0]
22nd Dec 2022, 8:27 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Thank you now I can understand...
22nd Dec 2022, 8:50 AM
YOGESHWARAN
YOGESHWARAN - avatar