-2

May I know how to build a CSS style parser/evaluator in JavaScript for below:

.book { width: calc(200px + 400px); }
.book h1 { font-size: 10em; }
div.book { color: blue; }
.book.green { background: green; }
.book[name="hello"] { color: pink; }
.book[data-name="hi"], .other-book { color: red; }
.book > a { text-decoration: none; }
.book a:nth-child(2) { color: purple; }
user21
  • 1,261
  • 5
  • 20
  • 41
  • 1
    Possible duplicate of [What does getElementsByClassName return?](http://stackoverflow.com/questions/10693845/what-does-getelementsbyclassname-return) – Sebastian Simon Feb 02 '16 at 23:18

1 Answers1

1

document.getElementsByClassName('box') actually returns a collection. You should specify a specific index inside square brackets like this

document.getElementsByClassName('box')[0].style.width = '100px';

This has to do with the difference between classes and ids. There can be multiple elements with the same class name, but ids are unique. The same formula as

document.getElementById

does not work with classes, because of the difference I mentioned above.

Although, this is best done through css.

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87