Jacob Gray Jacob Gray - 5 months ago 11x
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?


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";