Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

99
Views
Get first and last n items from a nodelist

I have a nodelist

    <ul>
        <li>One</li>
        <li>Two</li>
        <li>Three</li>
        <li>Four</li>
        <li>Five</li>
    </ul>
const slides = document.querySelectorAll('ul li');

I want to save copies of first and last 2 li elements to a variable.

const first2 = slides.slice(0, 2),
  last2 = slides.slice(-2);

All the answers I've seen suggest creating array from nodelist but I need these elements to remain a nodelist. How can I do this?

I want to create clones of these items, add a class to it and add it back to ul. So the final html should look like this

<ul>
    <li class="copy">One</li>
    <li class="copy">Two</li>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
    <li class="copy">Four</li>
    <li class="copy">Five</li>
</ul>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!