Home >Web Front-end >CSS Tutorial >How Can I Dynamically Change CSS Style Attributes Using JavaScript?
Dynamically Modifying Style Attributes with JavaScript
Suppose you have a defined CSS style sheet for a DIV element. The need arises to dynamically modify a specific attribute of that DIV using JavaScript. How can this be achieved effectively?
Simply Put...
To dynamically change a style attribute, use the following syntax:
document.getElementById("elementID").style.attributeName = "newAttributeValue";
Example:
document.getElementById("xyz").style.paddingTop = "10px";
This code successfully modifies the padding-top attribute of the DIV with the ID "xyz" to a value of "10px".
Alternate Notation for Style Properties:
In addition, you can also utilize a dash-notition for style properties:
document.getElementById("xyz").style["padding-top"] = "10px";
This alternative syntax allows you to specify style properties using their hyphenated CSS equivalents.
The above is the detailed content of How Can I Dynamically Change CSS Style Attributes Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!