Home > Web Front-end > CSS Tutorial > How Can I Dynamically Change CSS Style Attributes Using JavaScript?

How Can I Dynamically Change CSS Style Attributes Using JavaScript?

Linda Hamilton
Release: 2024-12-14 10:19:11
Original
343 people have browsed it

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";
Copy after login

Example:

document.getElementById("xyz").style.paddingTop = "10px";
Copy after login

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";
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template