<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?
usually <ul> tag contains only <li> tags. If you want to remove all <li> tags then $("#ulelementID"). html(""); will work.
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.
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.
The removeAttr() method removes one or more attributes from the selected elements.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With