Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript change Div style

Tags:

javascript

I want that part 1 onclick div style changes and part 2 again on click it comes back to normal. I tried doing so but I failed to achieve the part 2 results.

Following is the Javascript code

function abc() {     document.getElementById("test").style.color="red"; } 

After clicking the test div again, color should come back to defaulr color i.e. black...

like image 381
Sandbox E Avatar asked Apr 09 '12 09:04

Sandbox E


People also ask

How do I give a div a style?

The <div> tag defines a division or a section in an HTML document. The <div> tag is used as a container for HTML elements - which is then styled with CSS or manipulated with JavaScript. The <div> tag is easily styled by using the class or id attribute. Any sort of content can be put inside the <div> tag!

Can I use div in JavaScript?

Using JavaScript In vanilla JavaScript, you can use the native createElement() method to create an HTML <div> element and the appendChild() method to append the <div> element to another container.


2 Answers

function abc() {     var color = document.getElementById("test").style.color;     if (color === "red")          document.getElementById("test").style.color="black";     else          document.getElementById("test").style.color="red"; } 
like image 72
Yehuda Shapira Avatar answered Sep 27 '22 18:09

Yehuda Shapira


Using jQuery:

$(document).ready(function(){     $('div').click(function(){         $(this).toggleClass('clicked');     }); });​ 

Live example

like image 28
jacktheripper Avatar answered Sep 27 '22 18:09

jacktheripper