lanqy lanqy - 5 months ago 8
Javascript Question

how to use javascript to change div backgroundColor

The html below:

<div id="catestory">

<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 does't work

how to use javascript(not jquery or other js framework) to do this?

Edit:how to change the h2 backgroundColor too

Answer
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';
};