'Select all elements except the first [duplicate]
I would like to know how to use only JavaScript to select all elements except the first one.
My current approach:
const ps = document.querySelectorAll('div > p')
const [first, ...rest] = ps
rest.forEach(p => {
p.innerHTML = ""
})
<div>
<p><span>+</span>1</p>
<p><span>+</span>2</p>
<p><span>+</span>3</p>
</div>
This works, but it returns an array instead of a NodeList. I would like it to return a NodeList.
Solution 1:[1]
CSS Selector: :not(:first-child)
const ps = [ ...document.querySelectorAll('div > p:not(:first-child)') ]
console.log(ps.map(e => e.innerHTML));
<div>
<p><span>+</span>1</p>
<p><span>+</span>2</p>
<p><span>+</span>3</p>
</div>
Splice: ps.splice(0, 1);
const ps = [ ...document.querySelectorAll('div > p') ]
ps.splice(0, 1);
console.log(ps.map(e => e.innerHTML));
<div>
<p><span>+</span>1</p>
<p><span>+</span>2</p>
<p><span>+</span>3</p>
</div>
Solution 2:[2]
const ps = document.querySelectorAll("div > p:not(:first-child)");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Davide |
