Get first and last n items from a nodelist
Solution 1:
Do you mean something like this?
const slides = document.querySelectorAll("ul li");
const ul = document.querySelector("ul");
const temp = [];
slides.forEach(slide => {
const clone = slide.cloneNode(true);
clone.classList.add("red");
temp.push(clone);
});
temp.slice(0, 2).reverse().forEach(slide => {
ul.prepend(slide);
});
temp.slice(-2).forEach(slide => {
ul.appendChild(slide);
});
.red {
color:red;
}
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
Solution 2:
You can you selector like in CSS. In this case :first-child
and :last-child
const firstElement = document.querySelector('ul li:first-child');
console.log('firstElement', firstElement)
const lastElement = document.querySelector('ul li:last-child');
console.log('lastElement', lastElement)
ul li:first-child {
color:red;
}
ul li:last-child {
color:green;
}
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>