innerHTML not working in this particular script

Viewed 123

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. Please Help me out. Thanks you in Advance:) .

I have used JavaScript with Jquery.

<script>

$.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>
3 Answers

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;

getElementsByClassName returns an HTML Collection

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

This should work

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

Related