Objectives and outcomes

In this tutorial we are going learn to change the style of particular document element using javascript. This is done by using the document object in javascript. The example for the same is show below:





Click the button to see the change in background-color and text-color




HTML code:

<html>
<body>
<button id="ele">Click me!</button>
<div id="chn" style="background-color:brown; color:white;">
<br/>
<p><b>Click the button to see the change in background-color and font-color</b></p>
</div>
</body>
</html>





Javascript:

<script>
$(document).ready(function()
{
$("#ele").click(function()
{
if(document.getElementById("chn").style.color == "white")
{
document.getElementById("chn").style.color = "brown";
document.getElementById("chn").style.backgroundColor = "white";
}
else if(document.getElementById("chn").style.color == "brown")
{
document.getElementById("chn").style.color = "white";
document.getElementById("chn").style.backgroundColor = "brown";
}
});
});
</script>


In the above script we have attached the change style event with a div with id=chn. As soon as we click on the button with id=ele the background-color and font-color of the div gets reversed. We have done this by first creating the document object then selecting document element by id and then selecting the style attribute which we want to change.