Jacob Gray Jacob Gray - 2 years ago 102
HTML Question

Change font of multiple elements using document.getElementsByClassName()?

How do you change font in CSS using


I tried using:

document.getElementsByClassName("classname").style.fontFamily="Your font";

but it doesn't work.

I am using Firefox 27.0.1 and it is supposed to be supported so I don't think that is a problem. Is there something wrong with my code?

Answer Source

First of all note that it's .getElementsByClassName() not .getElementsByClass().

.getElementsByClassName() method returns a NodeList of matching elements, Therefore, you have to loop through the returned list to apply the attribute, as follows:

var list = document.getElementsByClassName("classname");

for (var i = 0; i < list.length; ++i) {
    list[i].style.fontFamily="Your font";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download