简体   繁体   中英

alter divs css with javascript

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

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

假设A标签将是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';

并改变风格使用

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM