How to Change the Style Attribute of an Element Dynamically.
It is easy to modify the style attribute of an element by employing JavaScript. The workings of this conversion are as follows. Firstly, getElementById is utilized to access the elements of document objects. After that, a button is created that occurs if the client pressed it. Therefore, the property of a specific element is accessed, and the user dynamically changes the style attribute of an element.
Syntax
Parameters
The description of the parameters is as follows:
- propertyName: specifies the name of property such as color, font-size, etc.
- propertyValue: represents the value to assign to the property of an element, e,g, “red”.
Example
An example is adapted to change the text color by accessing the style attribute of an element. The code is given below by considering the dynamic change of style attributes.
Code
<body>
<h2>An example to change the dynamic properties</h2>
<form action="" name="orderForm">
<input type="BUTTON" value="Press Button" onClick="pressBtn()" />
</form>
<script language=javascript type="text/javascript">
function pressBtn()
{
var myElement = document.getElementById("introtext");
myElement.style.color="red";
}
</script>
<p id="introtext">Welcome to JavaScript World"</p>
</body>
</html>
The description of the code is explained in a logical order.
- A button is created by passing the value “Press Button”.
- A “pressBtn()” method is attached to this button that is triggered when it is called.
- After that, the above method “pressBtn()” is written within <script> tags.
- In this method, myElement variable is utilized to save the element attributes.
- Finally, the style attributes of this element are dynamically changed when the pressBtn() method is called.
Output
After pressing the button “Press Button”, the pressBtn() method is triggered, which changes the style attribute of this specific element dynamically.
Finally, the black text color of “Welcome to JavaScript” is changed to red in the browser by utilizing the JavaScript pressBtn() method.
Conclusion:
First, the element is accessed using the getElementById, and then the document.style.property is employed to change the style attribute of the element. Lastly, a button is associated with it, and when this button has pressed, the style of the element changes. This article demonstrates the possible method to convert the style attribute in JavaScript.