-1

$(function(){
    $("#list li").slice(0, 1).show(); 
    $("#load").click(function(e){
        e.preventDefault();
        $("#list li:hidden").slice(0, 3).show(); 
    });
});
ul{background:pink; width:80%; height:auto; padding:2%; list-style-type:none;}

li{background:red; width:100%; margin:1%; color:white}

#load{color:white; background:red; text-decoration:none; margin:0% 0% 0% 40%; padding:1%;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li id=”list”>item 1</li>
<li id=”list”>item  2</li>
<li id=”list”>item 3 </li>
<li id=”list”>item  4</li>
<li id=”list”>item 5 </li>
<li id=”list”>item  6</li>
<li id=”list”>item  7</li>
<li id=”list”>item  8</li>
<li id=”list”>item  9</li>
<li id=”list”>item  10</li>
</ul>

<a href="#" id="load">Load More</a>

I'm trying to create a list that loads other items when the user clicks the button. The Jquery code above targets the "#list li", but for some reason it doesn't work when I click the button.

What am I doing wrong here?

Majora
  • 77
  • 7

1 Answers1

0
  • None of the items were hidden in the first place (though I assume this was an artifact of the question rather than your real code).
  • Duplicate IDs are invalid HTML; jQuery will only ever be able to access the first element with a given ID.
  • #list li would select a list item which is a child of #list, but in your case it's the same element (so should have been li#list).

Here's a corrected version, using classes instead of IDs:

$(function(){
    $("li.list").slice(0, 1).show(); 
    $("#load").click(function(e){
        e.preventDefault();
        $("li.list:hidden").slice(0, 3).show(); 
    });
});
ul{background:pink; width:80%; height:auto; padding:2%; list-style-type:none;}

li{background:red; width:100%; margin:1%; color:white; display:none}

#load{color:white; background:red; text-decoration:none; margin:0% 0% 0% 40%; padding:1%;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="list">item 1</li>
  <li class="list">item 2</li>
  <li class="list">item 3</li>
  <li class="list">item 4</li>
  <li class="list">item 5</li>
  <li class="list">item 6</li>
  <li class="list">item 7</li>
  <li class="list">item 8</li>
  <li class="list">item 9</li>
  <li class="list">item 10</li>
</ul>

<a href="#" id="load">Load More</a>
Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
  • Thank you, Daniel! This works perfectly. Was your solution down voted? Thank you everyone for your suggestions. – Majora Feb 06 '19 at 20:38
  • It did collect a downvote, not sure why but it happens sometimes, no big deal. Anyway, glad I could help! – Daniel Beck Feb 06 '19 at 20:42