开发者

alter divs css with javascript

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

<div id="some开发者_运维知识库div"><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..


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";


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


document.getElementById ( 'somediv' ).children[0].style.color = 'new color';

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


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


And to change the style use

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜