Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/458.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/css/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript如何选择元素并设置其样式_Javascript_Css_Parsing_Select_Styles - Fatal编程技术网

javascript如何选择元素并设置其样式

javascript如何选择元素并设置其样式,javascript,css,parsing,select,styles,Javascript,Css,Parsing,Select,Styles,我想知道如何用JavaScript为以下内容构建CSS样式的解析器/计算器: .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: r

我想知道如何用JavaScript为以下内容构建CSS样式的解析器/计算器:

.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; }

document.getElementsByClassName('box')
实际上返回一个集合。您应该在方括号内指定一个特定的索引,如下所示

document.getElementsByClassName('box')[0].style.width = '100px';
这与
ID
之间的差异有关。可以有多个元素具有相同的类名,但ID是唯一的。公式与

document.getElementById
不适用于类,因为我上面提到的差异


尽管这最好通过css来实现。

for.box>a的可能重复,我如何选择我想用JavaScript实现css样式的解析器/计算器。为什么?CSS用于样式化,JavaScript用于行为。