0

I would like to change the style of an element's links using JavaScript. The CSS would look like:

#element a:link {
    color: #000;
}

I know that you can change the style of the the element itself, as in:

elementObject.style.color = '#000';

Pseudo-code for what I want would be:

                 |
                 V
elementObject.[A:LINK].style.color = "#ff0000";

How can I do this?

Keith Pinson
  • 7,835
  • 7
  • 61
  • 104
Jesse Williams
  • 436
  • 4
  • 17

4 Answers4

1

the :link :visited are not true CSS elements, but part of the CSS rule, this means you need to edit the rule, change the rule or apply another class...

var css='#element a:link { color: #ff0000 }';
style=document.createElement('style');
if (style.styleSheet)
    style.styleSheet.cssText=css;
else 
    style.appendChild(document.createTextNode(css));
document.getElementsByTagName('head')[0].appendChild(style);
Dory Zidon
  • 10,497
  • 2
  • 25
  • 39
0

You can loop through links and set the one by one.

<script type='text/javascript'>
function new_window()
{
    var anchors = document.getElementsByTagName('a');
    for(var i = 0; i < anchors.length; i++)
    {
        anchors[i].style.color = '#000';
    }
}
window.onload = new_window;
</script>

The other way to create a wrapper div with the "wrapper" class name. Then replace its class name to "wrapper2" with JavaScript. After then the rules in the CSS like .wrapper a will be activated.

.wrapper a
{
    //normal code
}
.wrapper2 a
{
    color: #000;
}
Patartics Milán
  • 4,858
  • 4
  • 26
  • 32
0

select visited links is javascript isnt possible merely by a selector. have a look at Detect Visited Link In Chrome

and this http://archive.plugins.jquery.com/project/Visited

so if you wanna set the style of a visited/unvisited link using javascript loop through all the links in the body. checking wether they are visited and then apply style.

var as = document.getElementsByTagName('a');
for(var i=0;i<as.length;i++){
//check and set the style here
}
Community
  • 1
  • 1
Parv Sharma
  • 12,581
  • 4
  • 48
  • 80
0
function addCss(sel, css){
    S= document.styleSheets[document.styleSheets.length-1];
    var r= (S.cssRules!= undefined)? S.cssRules: S.rules;
    if(S.insertRule) S.insertRule(sel+'{'+css+'}',r.length);
    else if(S.addRule)S.addRule(sel,css,r.length);
}

 addCss('button:hover','background-color:blue;');
Abraham K
  • 624
  • 1
  • 8
  • 24