2

Can I change style of some div link. Here is what I mean

<div id="somediv"><a href="#">something</a>/div>

Lets say I have css like this :

#somediv a{
color:#000;
}

Now for instance upon some action such as mouse click on any element I want to change somediv a link css to

#somediv a{
color:#00ffff;
}

I know how to select div, by using Document.get.elementById('somediv')
Is it possible to select a by using above method or any other?

Thank you

DETAILS: Yes I know how to select it using jquery, or prototype .. I can't use any of those..

ant
  • 22,634
  • 36
  • 132
  • 182
  • Just to be clear: Do you want to change the style of the element itself, or do you want to change the style definition being applied to the element? The latter is more difficult than the former. – T.J. Crowder Dec 07 '09 at 15:04
  • 1
    Ah jQuery, it's like Godwin's law. – nickf Dec 07 '09 at 15:06
  • I'm not allowed to use jquery .. I updated my question sorry T.J - The second one :) – ant Dec 07 '09 at 15:07
  • Can you comment please why did I get negative vote ? – ant Dec 07 '09 at 15:42

6 Answers6

6

If you just want to apply a style to a particular element, it's very easy to do:

document.getElementById('whatever').style.color = '#f0f';

If you actually want to apply cascading styles (eg: #someDiv a), then it's not so easy (though it is definitely possible). I would suggest applying a new class to something, and having a pre-existing rule in your CSS.

CSS:

#someDiv a {
    color: #000;
}
#someDiv.awesome a {
    color: #f0f;
}

Javascript:

document.getElementById('someDiv').className = "awesome";
nickf
  • 537,072
  • 198
  • 649
  • 721
1

Yep, you can modify the actual CSS rules at runtime. See Totally Pwn CSS with Javascript for more details.

If you're using jQuery or YUI, there's some good info in question 1079237

Community
  • 1
  • 1
Dan F
  • 11,958
  • 3
  • 48
  • 72
1
document.getElementById ( 'somediv' ).children[0].style.color = 'new color';

assuming the A tag will be the first element inside your DIV

Jan Hančič
  • 53,269
  • 16
  • 95
  • 99
1

You could use CSS behaviors for this:

For instance:

#somediv a:hover
{
    color:#0ff;
}

Otherwise, you may create a dedicated class (used when an element is click for example):

#onclickclass
{
    color:#0ff;
}

Then in JavaScript, on onClick event, do:

document.getElementById('somediv').className = 'onclickclass';
Benoit
  • 680
  • 1
  • 6
  • 17
0

And to change the style use

document.getElementById('somediv').className = 'your-css-class';

Ben Fransen
  • 10,884
  • 18
  • 76
  • 129
0

If you really want to select the anchor you would have to then traverse the document.getElementById('somediv').children array.

As others have suggested though the simpler answer would be to set the className attribute on your div and let the CSS style cascade onto the anchor tag.

fyjham
  • 7,004
  • 2
  • 32
  • 40