Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JavaScript to change div backgroundColor

The HTML below:

<div id="category">    <div class="content">      <h2>some title here</h2>       <p>some content here</p>   </div>    <div class="content">      <h2>some title here</h2>       <p>some content here</p>   </div>    <div class="content">      <h2>some title here</h2>       <p>some content here</p>   </div>  </div> 

When mouseover the content of div then it's backgroundColor and the h2 (inside this div) backgroundColor change (just like the CSS: hover)

I know this can use CSS (: hover) to do this in modern browser but IE6 doesn't work.

How to use JavaScript (not jQuery or other JS framework) to do this?

Edit:how to change the h2 backgroundColor too

like image 379
lanqy Avatar asked Dec 09 '09 15:12

lanqy


People also ask

What is the code for changing the background in JavaScript?

body. style. background = color; } window. addEventListener("load",function() { changeBackground('red') });

Can you change color in JavaScript?

Answer: Use the JavaScript style property You can easily change the background color of a webpage i.e. the <body> element or any other element dynamically by using its style property in JavaScript.


1 Answers

var div = document.getElementById( 'div_id' ); div.onmouseover = function() {   this.style.backgroundColor = 'green';   var h2s = this.getElementsByTagName( 'h2' );   h2s[0].style.backgroundColor = 'blue'; }; div.onmouseout = function() {   this.style.backgroundColor = 'transparent';   var h2s = this.getElementsByTagName( 'h2' );   h2s[0].style.backgroundColor = 'transparent'; }; 
like image 175
Jacob Relkin Avatar answered Sep 28 '22 07:09

Jacob Relkin