0

I have the following:

<style>
    .el {color: blue;}
</style>

<div class="el">bla bla</div>
<div class="el">bla bla 123</div>

And i need to use JavaScript to change the color in .el. I know about document.styleSheets but that seems kind of crude, having to loop search for the class i want to change it that way. Isn't there some better (lighter) way to do this nowadays? Something like

document.stylesheets.getclass('.el').color = 'red';

Thanks.

Derek Henderson
  • 9,388
  • 4
  • 42
  • 71
user2079305
  • 121
  • 1
  • 6

2 Answers2

1

You're on the right track. The method you're looking for is getElementsByClassName, not getClass. It returns an array, and then you simply loop through the array and assign the new color.

var el = document.getElementsByClassName('el'),
    i;

for (i = 0; i < el.length; i += 1) {
    el[i].style.color = 'red';
}

Demo

P.S., obviously, this changes the style, not the stylesheet.

Derek Henderson
  • 9,388
  • 4
  • 42
  • 71
  • @user2079305: if you need to do without looping, use jquery like $(".el").css('color', 'red'); – Anoop Joshi P May 13 '13 at 10:58
  • Yes, you're right. There are so many browser compatibility issues with trying to change the stylesheet directly that it's not practicable. And it's not as if you can save the changed stylesheet on the server. – Derek Henderson May 13 '13 at 10:59
  • Well yes, after looking at alternatives, I think that this will be the best solution. Definitely better than stylesheet array crawl. – user2079305 May 13 '13 at 11:04
0

Try this:

var elem = document.getElementsByClassName('el');
            for (var i = 0; i < elem.length; i++) {
                elem[i].style.color = '#aaaaaa';
            }
Pritesh Tayade
  • 630
  • 4
  • 11