Hello Readers,
Usually, we need to add css property in HTML tag using Javascript.
Here I am describing different kinds of examples to adding style property using Javascript
1.) If you want to add single css property using Javascript, then you can use following example for the same task.
Example:
<!DOCTYPE html>
<html>
<body>
<h1>Add single CSS using Javascript</h1>
<p id="dummydemo">JavaScript can change the single style of an HTML element.</p>
<script type="text/javascript">
function setFunction() {
var data = document.getElementById("dummydemo");
data.style.fontSize = "25px";
data.style.color = "#ff0000";
data.style.fontStyle = "italic";
}
</script>
<button type="button" onclick="setFunction()">Click Here!</button>
</body>
</html>
2.) If you want to add multiple css property using javascript, then you can use any the following example.
Example:
<!DOCTYPE html>
<html>
<body>
<h1>Add multiple CSS using Javascript</h1>
<p id="dummydemo">JavaScript can change the multiple style of an HTML element.</p>
<script type="text/javascript">
function setFunction() {
document.getElementById("dummydemo").setAttribute(
"style", "font-size: 100px; font-style: italic; color:#ff0000;");
}
</script>
<button type="button" onclick="setFunction()">Click Here!</button>
</body>
</html>
Notice (In above examples: Example-1 and Example-2 ) that with the DOM notation, the quotation marks(" ") around the property names are optional, but with CSS notation they are required. If you are not using the quotation marks with property name, then you need to remove hyphen(-) from the property name and also need to capitalize first character after hyphen in property name. e.g.: you need to change font style to fontStyle OR font-size to fontSize.
Thanks
0 Comment(s)