artze artze - 3 months ago 8
Javascript Question

Italics font-style not working on element's class attribute

I'm working on a simple exercise: changing font-style by associating an element with a class. Below:

<html>
<head>
<title>DOM</title>
<style type="text/css">
#divAdvert {
font: 12pt arial;
}

.newStyle {
font-style: italic;
text-decoration: underline;
}
</style>
</head>
<body>
<div id="divAdvert">Here is an advertisement</div>
<script>
var divAdvert = document.getElementById("divAdvert");
divAdvert.className = "newStyle";
</script>
</body>
</html>


The above resulted in 'Here is an advertisement' with underline but without italic font style.

However, italic works if I included
font-style: italic;
under
#divAdvert


Why is that?

Answer

You have defined font property of CSS using #divAdvert and it gets preference over your .newStyle that has only font-style so if you want to add/alter any sub-property in CSS you need to define as my code snippet below:

Code Snippet

var divAdvert = document.getElementById("divAdvert");
divAdvert.className = "newStyle";
#divAdvert {
  font-size: 12pt;
  font-family: 'Arial', sans-serif;
}
.newStyle {
  font-style: italic;
  text-decoration: underline;
}
<div id="divAdvert">Here is an advertisement</div>

Comments