1

Possible Duplicate:
Changing a CSS rule-set from Javascript

I am creating a list of elements in my jsp page with the same class name. Say I am creating 4 elements with same class name as "someName". Now, I want to modify the style of these elements dynamically using javascript.i.e, when a style is changed for the class it should reflect in all the elements referenced by the class name.Also, I have to do this with IE8. Can this be accomplished?

Thanks

Community
  • 1
  • 1
GMG
  • 31
  • 3
  • Problem statement is unclear. Can you please post code snippet? – Parag Meshram Oct 18 '12 at 15:14
  • check this out, it's about changing classes on elements http://stackoverflow.com/questions/3452778/jquery-change-class-name – mrk Oct 18 '12 at 15:18
  • I can't use jQuery. Another big limitation is I have to achieve this using IE8, that too by using plain old javascript. – GMG Oct 21 '12 at 06:22

3 Answers3

1

Short answer: YES

Ah you also want to know how? Why haven't you asked for the how?

I give you an example in jQuery

$(".someName").css("background-color","green:);

That would change the background-color all elements with the class 'someName'

Sven Bieder
  • 5,515
  • 2
  • 21
  • 27
  • Thanks for your reply Sven. But, i have to use simple pure javascript without any jQuery thing. That too i have to make it IE8 compatible. – GMG Oct 21 '12 at 06:24
1

The best way to do this is to add an additional class to the relevant elements.

Javascript

var elements =  document.getElementsByClassName('oldClass');
for(var i = 0;i<elements.length;i++){
    elements[i].className += ' newClass' //dont forget the first space
}

CSS

oldClass{color:red;}
newClass{color:white; font-weight:bold;}

the jQuery solution is more elegant, but you can do it with plain ol' javascript too.

A F
  • 7,424
  • 8
  • 40
  • 52
-1

In general, I would do as @sven-bieder suggests, but to answer your specific question: check out this answer https://stackoverflow.com/a/1409250/45948

Community
  • 1
  • 1
roberkules
  • 6,557
  • 2
  • 44
  • 52
  • You referred the op to an internal link, which in turn refers to an external link....why??? – riwalk Oct 18 '12 at 15:21
  • The internal link is to see the SO question with the according answers. What's the problem with that? Is it the extra click that bothers you? – roberkules Oct 18 '12 at 15:22
  • Its the fact that your answer adds no value. -1 – riwalk Oct 18 '12 at 16:18
  • I pointed him to a valid answer, so what's your problem? And you're the one to decide if it's added value. Did you know you can change rules or do you know how to do it? I think it is added value. – roberkules Oct 18 '12 at 19:38
  • Just quit whining. I'm not going to argue over a downvote. – riwalk Oct 18 '12 at 20:57