views:

113

answers:

6

Hello everybody,

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..

A: 

And to change the style use

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

Ben Fransen
+6  A: 

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
Thank you nickf, you totally got it :)
c0mrade
+1  A: 

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

Dan F
+1  A: 
document.getElementById ( 'somediv' ).children[0].style.color = 'new color';

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

Jan Hančič
Thank you Jan, your solutions works as well. Hvala puno !!
c0mrade
Nema problema ;)
Jan Hančič
+1  A: 

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
A: 

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.

Tim Schneider