Ayushman Kumar
Ayushman Kumar

Reputation: 133

Why can’t I assign to `.innerHTML` of what `getElementsByClassName` returns?

I want to take every element of from the API and show it in different classes. I am getting the result in my Console but not on the page.

I have used JavaScript with jQuery.

$.getJSON('https://api.noopschallenge.com/wordbot?count=5', function (data) {
  console.log(data);     

  for (let i = 0; i < 5; i++) {
    var box = document.createElement("div");
    box.setAttribute("class", i);
    document.body.appendChild(box);
    let dat = `${data.words[i]}`;
    let a = i.toString();
    document.getElementsByClassName(a).innerHTML = dat;
    console.log(dat);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

Upvotes: 2

Views: 198

Answers (3)

Ram Segev
Ram Segev

Reputation: 2571

instead of
document.getElementsByClassName(a).innerHTML = dat; you can use box.innerHTML = dat;

Upvotes: 1

Mamun
Mamun

Reputation: 68933

getElementsByClassName() returns an array-like object of all child elements which have all of the given class names, you have to use proper index:

document.getElementsByClassName(a)[0].innerHTML = dat;

Upvotes: 4

user5616242
user5616242

Reputation:

getElementsByClassName returns an HTML Collection

for (let element of document.getElementsByClassName(a)) {
    element.innterHTML = dat
}

This should work

Upvotes: 1

Related Questions