sum man
sum man

Reputation: 73

use js replace font family with class name

I found some code can change the font family with ID. But i want to use this in my website and replace the font family with class.

<!DOCTYPE html>
<html>
<body>
<div class="myP">This is a paragraph.</div>
<script>
    document.getElementsByClassName("myP").style.fontFamily = "Impact,Charcoal,sans-serif";
</script>
</body>
</html>

Upvotes: 0

Views: 1236

Answers (2)

Vladu Ionut
Vladu Ionut

Reputation: 8193

You can use the className and in CSS define your font styles properties

var elements= document.getElementsByClassName("myP")
for (var i = 0; i < elements.length; i++) {

elements[i].className +=" myFont";
}
.myFont{
  font-family:Impact,Charcoal,sans-serif;
}
<div>This is a paragraph.</div>
<div class="myP">This is a paragraph.</div>
<div class="myP">This is a paragraph.</div>

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

document.getElementsByClassName() function returns HTMLCollection object.
In case of multiple paragraphs you need to iterate through that object or to access the needed element directly by its position:

...
document.getElementsByClassName("myP")[0].style.fontFamily = "Impact,Charcoal,sans-serif";  

https://jsfiddle.net/e2xzs9o2/

Upvotes: 1

Related Questions