I just learned this so I thought I would reply. The ‘getElementsBy’ methods give you an ‘array like’ object. So you need to use a bracket notation to select the exact one you want.
So, the [0] just means you want the first (remember that arrays start counting at zero) element with the ‘message’ class
As @Newman5 has explained it well, getElementsByClassName() will return an 'array like’objects. Because if you actually read it carefully, it says Elements as in plural… It’s also the fact that you can use classes multiple times.
Thank you so much for explaining.
It was bit weird for me since it calls the class name by using “ByClassName”.
Another question is,
if the code is like this
<p class="message box">
The message will go here
</p>
<h2 class="message">
Testing
</h2>
Do you mean that getElementsByClassName("message")[0] will get me the <p>
tag instead of the <h2> ?
Yes, because the <p> tag has the message and box class. So it will grab that paragraph too. Remember, that you can add multiple classes to 1 element by seperating them with a space.