gfrey gfrey - 1 month ago 10
CSS Question

A more elegant solution for :nth-child content replacement

I am new to jQuery and I would like to know if there is a more elegant solution for this:

$( "ul li:nth-child(1) a span" ).append( "01" );
$( "ul li:nth-child(2) a span" ).append( "02" );
$( "ul li:nth-child(3) a span" ).append( "03" );
$( "ul li:nth-child(4) a span" ).append( "04" );
$( "ul li:nth-child(5) a span" ).append( "05" );
$( "ul li:nth-child(6) a span" ).append( "06" );
$( "ul li:nth-child(7) a span" ).append( "07" );
$( "ul li:nth-child(8) a span" ).append( "08" );
$( "ul li:nth-child(9) a span" ).append( "09" );
$( "ul li:nth-child(10) a span" ).append( "10" );

Answer

Use the append callback function, where the first argument i represents the current element index (starting at 0, therefore do some i=i+1;. I used ++i)

$("ul li a span").append(function(i) {
  return ++i>9 ? i : "0"+i;            // Print `++i` and add leading "0" if needed
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
</ul>

In JS ES6 it would look like:

Array.from(document.querySelectorAll('ul li a span'), (el, i) => {
   el.insertAdjacentHTML("beforeend", ++i>9 ? i : "0"+i );
});
<ul>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
  <li><a>LI <span></span></a></li>
</ul>

Comments