Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the last <li></li> using Jquery?

Tags:

jquery

  <div id="q">
    <ul><li>
    <table><tr><td>Question 1</td><td><input type="text" name="question1" size="60" /></td></tr>
   <tr><td>Answer:</td><td><input type="text" name="answer1" size="8" /></td></tr>
    </li></ul>
</div>

<input class="btn" id="addquestion"  type="button"  value="Add Question" />
<input class="btn" id="removequestion"  type="button"  value="Remove Question" />
<script>


 $('#addquestion').click(function() {
 var $question_number = $('#q li').size() + 1;

   $html='<li><table><tr><td>Question '+$question_number+'</td><td><input type="text" name="question'+$question_number+'" size="60" /></td></tr>\
   <tr><td>Answer:</td><td><input type="text" name="answer'+$question_number+'" size="8" /></td></tr></li>';
  $('#q ul').append($html);
   });

  $('#addquestion').click(function() {
$('#q li:last').remove();
}); 
</script>

$('#q li:last').remove(); doesn't work. What's wrong?

like image 538
Steven Avatar asked Nov 15 '09 06:11

Steven


People also ask

How remove Li tag in jQuery?

usually <ul> tag contains only <li> tags. If you want to remove all <li> tags then $("#ulelementID"). html(""); will work.

How do you delete something in jQuery?

jQuery remove() Method The remove() method removes the selected elements, including all text and child nodes. This method also removes data and events of the selected elements. Tip: To remove the elements without removing data and events, use the detach() method instead.

How remove and append in jQuery?

jQuery uses: . append(); and . remove(); functions to accomplish this task. We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.

What jQuery method is used to completely remove attributes from elements?

The removeAttr() method removes one or more attributes from the selected elements.


1 Answers

If you want to remove the last li element inside #d, you can simply use the :last selector:

$('#q li:last').remove();

If you want to remove every last li child of it's immediate parent (ul elements if you have more than one), you can use the :last-child selector:

$('#q li:last-child').remove();
like image 132
Christian C. Salvadó Avatar answered Oct 06 '22 22:10

Christian C. Salvadó