user2239972
user2239972

Reputation: 45

document.getElementsByClassName for multiple classes?

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

Upvotes: 0

Views: 3428

Answers (2)

user2239972
user2239972

Reputation: 45

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!

Upvotes: 1

Ionut Necula
Ionut Necula

Reputation: 11472

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>

Upvotes: 3

Related Questions