LearnFast.Ninja

JavaScript class name change using onclick with css style

Write css class. Write JavaScript function. Write div with id name and call the function with onclick event at the button. Test our working example.

Step 1: Write css class. 

.Lime {

    background-color: Lime;

    border: 1px solid black;

    padding: 10px;

}


Step 2: Write JavaScript function. 

function Change_Class_Name(My_Element, My_Class) {

    My_Element.className = My_Class;

}


Step 3: Write div with id name and call the function with onclick event at the button. 

<div id="Div_1">

    I am Div_1

</div>

<br />

<input type="button" value="Change class name" onclick="Change_Class_Name(Div_1, 'Lime');" />


Working Example:

<html>

<head>

    <title>Change class name</title>

    <style type="text/css">

        .Lime {

            background-color: Lime;

            border: 1px solid black;

            padding: 10px;

        }

    </style>

    <script type="text/javascript">

        function Change_Class_Name(My_Element, My_Class) {

            My_Element.className = My_Class;

        }

    </script>

</head>

<body>

    <div id="Div_1">

        I am Div_1

    </div>

    <br />

    <input type="button" value="Change class name" onclick="Change_Class_Name(Div_1, 'Lime');" />

</body>

</html>


Result: 


Tags

javascript

class