I'm trying to select the content inside an HTML tag except its last two children.
This is what I did so far
main > *:nth-last-child(n + 3) {
color: red;
}
<main>
<p>Lorem 1</p>
<p>Lorem 2</p>
<p>Lorem 3</p>
<p>Lorem 4</p>
<p>Lorem 5</p>
</main>
I'm trying to select the content inside an HTML tag except its last two children.
This is what I did so far
main > *:nth-last-child(n + 3) {
color: red;
}
<main>
<p>Lorem 1</p>
<p>Lorem 2</p>
<p>Lorem 3</p>
<p>Lorem 4</p>
<p>Lorem 5</p>
</main>
Above code does exactly what it should do, but the weird thing is the following one.
I created a script which logs on the browser console the result of following expression
document.querySelector('main > *:nth-last-child(n + 3)')
I expected to get the main tag with all its children but the last two, but I get the first child instead.
you can find a code sandbox here.
What am I doing wrong?
1 Answer
Reset to default 1you are confusing querySelector()
method and querySelectorAll()
document
.querySelectorAll('main > *:nth-last-child(n + 3)')
.forEach( e => console.log(e.textContent ))
;
main > *:nth-last-child(n + 3) {
color: red;
}
<main>
<p>Lorem 1</p>
<p>Lorem 2</p>
<p>Lorem 3</p>
<p>Lorem 4</p>
<p>Lorem 5</p>
</main>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745048688a4608251.html
querySelector
, which has the explicit purpose to return at most one element, in a situation where you want to select multiple elements, which means you of course need to usequerySelectorAll
instead. – C3roe Commented Mar 4 at 12:24