<html>
<body>
<div> Mango </div>
<div> Apple </div>
</body>
</html>
现在我想选择第二个div,它是使用CSS符号的“Apple”。CSS“>”选择器来选择特定格
我写符号这样:: html > body > div[2]
<html>
<body>
<div> Mango </div>
<div> Apple </div>
</body>
</html>
现在我想选择第二个div,它是使用CSS符号的“Apple”。CSS“>”选择器来选择特定格
我写符号这样:: html > body > div[2]
$('body div:nth-child(2)')
在支持HTML5的浏览器中使用如下
div:nth-child(2)
{
background:#ff0000;
}
使用JavaScript的唯一途径,而无需使用库,使用CSS符号进行选择是使用document.querySelector()
或document.querySelectorAll()
;两种方法之间的区别在于第一个querySelector()
返回单个节点(第一个元素)与传入的选择器匹配,而第二个节点返回包含所有匹配该选择器的元素的NodeList。
为了风格元素,例如,使用querySelctor()
:
document.querySelector('body > div:nth-child(2)').style.color = 'red';
为了风格元素,再作为一个例子,使用querySelectorAll()
:
var elements = document.querySelectorAll('body > div:nth-child(2)');
for (var i = 0, len = elements.length; i < len; i++) {
elements[i].style.color = 'red';
}
或者使用Array.prototype.forEach()
:
var elements = document.querySelectorAll('body > div:nth-child(2)');
[].forEach.call(elements, function(a){
a.style.color = 'red';
});
替代选择(如果你想样式的所有div
元素不的:first-child
:。
/* selects all div elements that are immediate child of the body
body element and are later-siblings of the div that is the
':first-child' */
body > div:first-child ~ div
JS Fiddle demo using querySelectorAll()
(with added div
elements to illustrate) JS Fiddle demo using querySelector()
(with added div
elements to illustrate)
或者:
/* Selects all div elements that are the adjacent sibling of
another div element, that is also an immediate child of
the body element */
body > div + div
JS Fiddle demo using querySelectorAll()
(with added div
elements to illustrate)。 JS Fiddle demo using querySelector()
(with added div
elements to illustrate)。
这些方法,使用querySelector()
和querySelectorAll()
不这样做,但是,工作在Internet Explorer小于9版本(虽然IE 8是“不完全的”,因此可以报价足够的相容性)。
参考文献:
请出示你的HTML看起来像 –
请分享你的HTML和CSS代码首先 –
显示你的HTML代码 – throrin19