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 im blind and dont see a very simple mistake in my code
Thanks in advance
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.
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;
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>