-2

I know there are a lot of questions regarding the getElementsByClassName not working, however I browsed through many and coudldnt find an answer for my situation.

Basically I have the following code:

<script>

var res = localStorage.getItem('img');
    if(res == null){
            const myList = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
            res  = myList[Math.floor(Math.random() * myList.length)];
            localStorage.setItem('img', res);
        }
console.log(res);

document.getElementsByClassName("emoji").innerHTML = res

And several spans with same class:

<span class="emoji" style="font-size: 40px !important;"></span>

The problem is that the "res" doesn't print anything in span.

The console log prints everything fine and LS stores the information perfectly .

I have tried with ID's:

document.getElementsById("emoji").innerHTML = res

And it works perfectly, however only with the first div (as it should i suppose).

What could I be doing wrong in this situation?

Maybe I am not able to see a very simple mistake in my code.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
  • You have to put `document.getElementsByClassName("emoji")[0].innerHTML` because `getElementsByClassName` method of Document interface returns an array-like object of all child elements which have all of the given class name. – Faheem azaz Bhanej Feb 12 '22 at 08:25
  • 1
    `document.querySelectorAll('.emoji').forEach(span => span.textContent = res)` – mplungjan Feb 12 '22 at 17:07

3 Answers3

0

If you specify classname so you have to give index to the class as it puts response only in the first element in the case of id, it is unique but in case of class you have to specify.

document.getElementsByClassName("emoji")[0].innerHTML = res;
Yves Kipondo
  • 5,289
  • 1
  • 18
  • 31
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
-1

Multiple elements can have the same class name. getElementsByClassName returns an array of elements that have the class name (it's Elements not Element). So if you have only 1 element with that class name, you can do document.getElementsByClassName("emoji")[0].innerHTML = res.

Amir
  • 996
  • 7
  • 17
-2

getElementByClassName always return array of element, usually can read an element from array as index basis, also similar way can get the element from getElementByClassName.Pls see the below snippet.

const myList = ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''];
var res  = myList[Math.floor(Math.random() * myList.length)];
document.getElementsByClassName("emoji")[0].innerHTML = res
<span class="emoji" style="font-size: 40px !important;"></span>
Ganesh R
  • 59
  • 3