Reputation: 14172
How do you change font in CSS using document.getElementsByClassName()
?
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?
Upvotes: 0
Views: 1570
Reputation: 329
getElementsByClassName() returns an array-like collection of elements. Iterate over it like you would with a real array:
var elements = document.getElementsByClassName("classname");
for(var i = 0; i < elements.length; i++) {
elements[i].style.fontFamily="Times New Roman";
}
If you prefer something shorter, consider using jQuery:
$('.classname').css('fontFamily', 'Times New Roman');
Upvotes: 1
Reputation: 3384
Use .getElementsByClassName()
instead of .getElementsByClass()
.
Also, document.getElementsByClassName()
returns an array of all child elements which have all of the given class names. Since it returns an array, you need to iterate through all the elements of the array like this:
elems = document.getElementsByClassName("classname")
for(elem in elems){
elem.style.fontFamily="Your font";
}
Upvotes: 1
Reputation: 101
Use this instead:
document.getElementsByClassName("classname").style.font="bold 20px Your Font";
If you are ok with using jQuery use:
$('.classname').css("font-family", 'Your Font');
Upvotes: -1
Reputation: 99564
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";
}
Upvotes: 2