Home >Web Front-end >JS Tutorial >How Can I Dynamically Modify the Styles of Externally Styled HTML Elements with JavaScript?
When working with HTML elements that are styled externally using CSS, it's often necessary to dynamically modify their appearance through JavaScript. One approach to achieve this is by manipulating the element's 'style' attribute.
Typically, this is done by referencing the element using its ID or class, and then appending the necessary style property and value to the element's style attribute. However, certain subtleties can arise depending on the specific method used to locate the element.
Consider the following example:
<p class="home" onclick="selectHome()">Home</p>
function selectHome() { document.getElementsByClassName("home").style += "background-color:green;"; }
The intent here is to change the background color of the paragraph (with class "home") to green upon clicking. However, this code often fails due to incorrect syntax.
To correctly modify the style, use the following syntax:
document.querySelector(".home").style.backgroundColor = "green";
Using .querySelector() instead of .getElementsByClassName() has several advantages:
The above is the detailed content of How Can I Dynamically Modify the Styles of Externally Styled HTML Elements with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!