0

When you write real CSS you could do

.blue { color: blue; }

and if you added the class "blue" to an element after loading, it would turn blue.

In JavaScript you would have to do something like

var blue = document.getElementsByClassName('blue');
for (var i = 0; i < blue.length; i++)
     blue[i].style.setProperty('color', 'blue');

The problem with the JavaScript version is if you did

document.getElementById('someId').className += " blue";

it would have the class blue, but it would not turn blue. Is there any way (preferably simple) to add the style to the selector rather then directly to the elements with that selector?

McKayla
  • 6,879
  • 5
  • 36
  • 48
  • I don't understand your dislike towards css? CSS is a great tool for separating style and logic (which is Javascript). Just make the class in css and add it with javascript! – Andrew Jackman Feb 19 '11 at 08:21
  • its not object oriented. Splitting the data in two files makes it less encapsulated. Seperate style and logic within your javascript file. – Oliver Watkins Jun 11 '13 at 10:19

3 Answers3

2

The most common way is defining .blue { color:blue; } in the CSS beforehand, then adding the class to the element via JS. That way styles are in the CSS and only class names are in the JS, making it more flexible instead of hardcoding dozens of css keys/values in the JS.

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
1

See this question. You can add a <style> element via JavaScript.

Community
  • 1
  • 1
Nicholas Riley
  • 43,532
  • 6
  • 101
  • 124
  • That could get messy very easily though. I thought about that, and it would take a very thoroughly thought out algorithm to make sure properties/selectors aren't duplicated. I'm going to try it but I have no idea what the outcome will be. Wish me luck. xD – McKayla Feb 19 '11 at 07:27
  • It all depends on the context you're using it; I assumed it was your own Web page so you could know what classes were defined. You could add a unique ID or the time to the class name, if you were really worried about it working in any web page. – Nicholas Riley Feb 19 '11 at 07:30
1

The HTML

<div id="test">This will turn blue</div>
<button onclick="addClass()" >add Class </button>

The Javascript

function addClass(){
    document.getElementById('test').className += 'blue';
}

The CSS

.blue{
     color:blue;
}

This works in FF IE7 and Chrome. Perhaps there is something else going on in your code which is stopping this from working.

Gary Ryan
  • 744
  • 3
  • 8
  • 19
  • People aren't getting that I don't want to use CSS. I want to figure out how to do that in PURE JavaScript. Nothing else, but HTML. – McKayla Feb 19 '11 at 08:11