I don't understand a syntax in getElementsByClassName

Tell us what’s happening:

What is the [0] for inside the document.getElementsByClassName(“message”)[0].textContent??
Thank you.

Your code so far

document.addEventListener('DOMContentLoaded', function(){
  document.getElementById('getMessage').onclick = function(){
    // Add your code below this line

document.getElementsByClassName("message")[0].textContent = "Here is the message";
    // Add your code above this line

body {
  text-align: center;
  font-family: "Helvetica", sans-serif;
h1 {
  font-size: 2em;
  font-weight: bold;
.box {
  border-radius: 5px;
  background-color: #eee;
  padding: 20px 5px;
button {
  color: white;
  background-color: #4791d0;
  border-radius: 5px;
  border: 1px solid #4791d0;
  padding: 5px 10px 8px 10px;
button:hover {
  background-color: #0F5897;
  border: 1px solid #0F5897;

<h1>Cat Photo Finder</h1>
<p class="message box">
The message will go here
<button id="getMessage">
  Get Message

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36.

Challenge: Change Text with click Events

Link to the challenge:

Hey Summer,

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


Hey @Summerflowerling :wave:,

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.



Yes, it’s an ‘array like’ object Collection.

Here’s an article about HTMLCollection:


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

<h2 class="message">

Do you mean that getElementsByClassName("message")[0] will get me the <p>
tag instead of the <h2> ?

Hi Newman5
Thank you for helping! =)

I tried it on codePen, and the answer is yes.
I understand it now. Thank you. =)

1 Like

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.

1 Like