If I have ten items in a list, how can I dynamically add a class (with jQuery) to the first half of them?
Input:
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
Desired output:
<ul>
<li class="first-half">1</li>
<li class="first-half">2</li>
<li class="first-half">3</li>
<li class="first-half">4</li>
<li class="first-half">5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
A general solution would be:
If you’re sure you will always have an even number, you can omit
Math.floor, and remember, there is alsoMath.ceilif you would prefer to round up.You can try it here.