+ 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; }
3 ответов
+ 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;
+ 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]
+ 1
Thank you now I can understand...