2

I have something like this:

-HTML-

<table>
<tr class="x" onMouseOver="light(this)">
  <td>
    <a href="x">Link</a>
  </td>
  <td>
    Text
  </td>
</tr>
</table>

-CSS-

.x a{
  color: black;
}

-Javascript-

function light(x){
  x.style.color="red";
}

Now, the function works correctly, but my a tag doesn't changes his color. Is there a way to make Javascript modify the attribute color of the CSS rule .x a?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
Federinik
  • 523
  • 4
  • 20
  • 1
    You can use the `:hover` pseudo-selector if you're just changing colors when people hover the links. – Fabrício Matté Sep 12 '12 at 15:54
  • since your css is styling the `a` element directly, you would have to style use javascript to style the `a` element directly in order to override the css definition. It's part of its cascading nature. – Shmiddty Sep 12 '12 at 15:56
  • See http://stackoverflow.com/questions/566203/changing-css-values-with-javascript – Lunik Sep 12 '12 at 15:56

4 Answers4

0

This should do the trick

x.children[0].children[0].style.color="red";

You can define a :hover style in the CSS for the link too

a:hover {
    color: red;
}

That will change the links color when you hover over it (the link).

.x:hover a { }

will apply a style to the link when you hover over .x

sachleen
  • 30,730
  • 8
  • 78
  • 73
0

This might be more suitable:

.x:hover {color:red}
.x:hover a{color:red}

This will override the link's colour when the row is hovered over, making the onMouseOver function unnecessary.

Note that it may fail in IE6, but personally I've never had any problems making things other than links :hover in that browser...

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • IE6 shouldn't even be mentioned anymore honestly. Just to point out however IE6 and below do not support pseudo class `:hover` on anything but a tags. – Loktar Sep 12 '12 at 16:01
  • That makes compleltely useless the Javascript function and has a better effect! CSS's power. Thank you – Federinik Sep 14 '12 at 07:03
0

Live Demo

This will change all the links that are children to red.

function light(x){
  var elems = x.getElementsByTagName("a");
    for(var i=0; i < elems.length;i++){
        elems[i].style.color="red";
    }
}​

Although I highly suggest using the :hover psuedo class like others have mentioned.

Loktar
  • 34,764
  • 7
  • 90
  • 104
0

-HTML- wrap your tr with in <table> tag, and convert to lowercase your onmouseover event attribute.

<table>
<tr class="x" onmouseover="light(this)">
  <td>
    <a href="x">Link</a>
  </td>
  <td>
    Text
  </td>
</tr>
</table>

-Javascript- change you javascript function body for select to a tag

function light(x){
  x.getElementsByTagName("a")[0].style.color="red";
}
Krishna Kumar
  • 2,101
  • 1
  • 23
  • 34