VicToR Sava
VicToR Sava

Reputation: 101

Change color of all links with class X JavaScript

Link with example

I am using the following function:

<div align="center"><a href="#" onclick="changeColor('A'); return false;">A</a>
<script>
    function changeColor(id)
    {
        document.getElementById(id).style.color = "#FFF"; // forecolor
        document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
    }
</script>

When, for example, I click on A on the page with the example, only the first link is changing colors because the script is changing colors by id. How can I change all link colors by class?

What I want is when I click on A, all links with class A should change their color, and when I click B, all links with class B should change their color, etc.

Upvotes: 0

Views: 1486

Answers (1)

adeneo
adeneo

Reputation: 318322

function changeColor( _class ) {
    var elems = document.getElementsByClassName( _class );
    for (var i=elems.length; i--;) {
        elems[i].style.color = "#FFF";
        elems[i].style.backgroundColor = "#ff0000";
    }
}

FIDDLE

Change the function to the above, and pass a class to it instead ?

jQuery version:

$('div[align="center"] > a').on('click', function(e) {
    e.preventDefault();
    $('.' + $.trim($(this).text())).css({color: '#fff', backgroundColor: '#ff0000'});
});

with HTML

<div align="center"><a href="#">A</a></div>

FIDDLE

Upvotes: 2

Related Questions