<html>
<body>
<div> Mango </div>
<div> Apple </div>
</body>
</html>
Now I want to select second div which is "Apple" using CSS notation.
I am writing notation like this :: html > body > div[2]
In HTML5 supported browsers use like below
div:nth-child(2)
{
background:#ff0000;
}
$('body div:nth-child(2)')
在这里试试: http : //jsfiddle.net/D6w3g/
With JavaScript the only way, without using a library, to select with CSS notation is to use document.querySelector()
or document.querySelectorAll()
; the difference between the two methods is that the first, querySelector()
returns a single node, the first element, that matches the passed-in selector, whereas the second, querySelectorAll()
returns a NodeList, comprising of all the elements that match that selector.
To style elements, for example, using querySelctor()
:
document.querySelector('body > div:nth-child(2)').style.color = 'red';
To style elements, again as an example, using 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';
}
Or using Array.prototype.forEach()
:
var elements = document.querySelectorAll('body > div:nth-child(2)');
[].forEach.call(elements, function(a){
a.style.color = 'red';
});
Alternative selectors (if you want to style all div
elements that aren't the :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) .
Or:
/* 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) .
These approaches, using querySelector()
and querySelectorAll()
do not, however, work under Internet Explorer less than version 9 (though IE 8 is 'incomplete,' so may offer sufficient compatibility).
References:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.