0

I'm a little stuck, please help.

<script>  
    var language = '#LanguageCode#-#CountryCode#';
    if(language === 'en-gb'){
      document.getElementsByClassName('apple')[0].innerHTML = '<img src="english-apple.svg"/>';    
      document.getElementsByClassName('android')[0].innerHTML = '<img src="english-android.svg"/>'; 

    } else if(language === 'nb-no'){
         document.getElementsByClassName('apple')[0].innerHTML = '<img src="norwegian-apple.svg"/>';  
         document.getElementsByClassName('android')[0].innerHTML = '<img src="norwegian-android.svg"/>'; 
    }   
</script>

This works a treat, but when I try to add another class to document.getElementsByClassName, it doesn't work.

Something like this:

document.getElementsByClassName('apple bottomapple')[0].innerHTML = '<img src="english-apple.svg"/>';  

In the other class I'm trying to add, there's an image with the same naming e.g. english-apple.svg. I need both classes to run at the same time if(language === 'nb-no') is true.

Any help will be much appreciated.

Thanks

Jai
  • 74,255
  • 12
  • 74
  • 103
user2239972
  • 45
  • 1
  • 8
  • Possible duplicate of [Javascript - how to get elements with multiple classes](http://stackoverflow.com/questions/7184562/javascript-how-to-get-elements-with-multiple-classes) – rkeet Mar 03 '17 at 11:28
  • Second class definitely exists and I've copied it 100x to make sure – user2239972 Mar 03 '17 at 11:31

2 Answers2

3

Ok. So the problem here is this:

document.getElementsByClassName('apple bottomapple') will work for:

<div class="apple bottomapple"></div>

But it will not work for this:

<div class="apple"></div>
<div class="bottomapple"></div>

So you have one approach here that cames across my mind now. You can use document.querySelectorAll() method:

var divs = document.querySelectorAll('.apple, .bottomapple');
for(var i = 0; i < divs.length; i++) {
  divs[i].innerText = 'test ' + i;
}
<div class="apple"></div>
<div class="bottomapple"></div>
Ionut Necula
  • 11,107
  • 4
  • 45
  • 69
1

Someone put an answer here but now it's gone, wanted to thank them.

This worked for me:

[...document.querySelectorAll('.apple,.bottomapple')].map(x => x.innerHTML = '');

Thanks everyone!

user2239972
  • 45
  • 1
  • 8