SimpleTuts.com

Change attributes and styles in JavaScript

In JavaScript, you can change an HTML element's attribute using HTML attribute names and modify its styles using the `style` property, allowing dynamic updates to elements' behavior and appearance directly from script.



<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- Change attribute values -->
    <img src="nature1.webp" alt="" width="500" id="mypic">
    <br><br>
    <button onclick="document.getElementById('mypic').src='nature2.webp'">
    Change image</button>
    <button onclick="document.getElementById('mypic').src='nature1.webp'">
    Change back</button>
    <button onclick="document.getElementById('mypic').width='700'">
    Change width</button>
    
    <!-- Change CSS styles-->
    <h1 id="demo">Change my styles</h1>
    <button onclick="document.getElementById('demo').style.color='red'">
    Change color</button>
    <button onclick="document.getElementById('demo').style.backgroundColor='yellow'">
    Change background color</button>
    <button onclick="document.getElementById('demo').style.fontSize='50px'">
    Change font size</button>
</body>
</html>
 
    
Run Code