Alex Newbie Alex Newbie - 5 months ago 21
jQuery Question

iterate through li elements then .addclass css on some li elements

I'm iterating through li elements then applying css on some li elements that meets my criteria.

lets say i have a 15 total of li elements in ul then i will css class using javascript .addclass

hide_me
on li count 11 to 15.

this is the html:

<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
<li>item 5</li>
<li>item 6</li>
<li>item 7</li>
<li>item 8</li>
<li>item 9</li>
<li>item 10</li>
<li>item 11</li>
<li>item 12</li>
<li>item 13</li>
<li>item 14</li>
<li>item 15</li>
</ul>


this i want to make using JavaScript/jquery

<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
<li>item 5</li>
<li>item 6</li>
<li>item 7</li>
<li>item 8</li>
<li>item 9</li>
<li>item 10</li>
<li class="hide_me">item 11</li>
<li class="hide_me">item 12</li>
<li class="hide_me">item 13</li>
<li class="hide_me">item 14</li>
<li class="hide_me">item 15</li>
</ul>


So far i came up with this JavaScript code but its not working.

my Javascript:

<script>
$(document).ready(function(){
$.each($('.items'), function() {
var children = $(this).find(">li");
var count_items = children.length;

for (var items = 11; items < count_items; items++) {
//console.log(items); //output 11, 12, 13, 14, 15
$(".items li:nth-of-type("+ items +")").addClass('.hideme'); // this is css selector by nth-type
}
});
});
</script>

Answer

$('ul li:gt(9)').addClass('addedclass')
.addedclass{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
    <li>item 4</li>
    <li>item 5</li>
    <li>item 6</li>
    <li>item 7</li>
    <li>item 8</li>
    <li>item 9</li>
    <li>item 10</li>
    <li>item 11</li>
    <li>item 12</li>
    <li>item 13</li>
    <li>item 14</li>
    <li>item 15</li>
</ul>

  1. Use :gt() selector. No need to iterate the li
  2. Index start at 0

Description: Select all elements at an index greater than index within the matched set.

Comments