Reputation: 1495
I have a UL LI list, and when user clicks on the LI, a button will be shown beside the LI using append. A class "selected" will be assign to the li as well. When user clicks on another LI, the previous LI with button should be removed, and the button will appear on the newly clicked LI. However I can't seem to be able to remove the button for the prev LI.
I would like to just remove the button from the previous LI, and maintain the button at the newly selected LI. How can I achieved that? My code is as below.
Thanks in advance.
$("ul#optionList li").on("click", function(){
var test= $(this).attr('id');
$("ul#optionList li").removeClass('selected');
$(this).addClass('selected');
// append the button to the LI
$(this).append("<a href='javascript:void(0);' class='checkanswer2' id='"+test+"'>Check Answer</a>");
$(this).children("a").remove(); // this will caused all the buttons to be removed, not just removing the previous selected LI
});
Upvotes: 0
Views: 1116
Reputation: 74738
Try to do this:
$('ul#optionList').find('.checkanswer2').remove(); // remove the other anchors
$(this).append("<a href='javascript:void(0);' class='checkanswer2'...");
you can remove the anchors with class name .checkanswer2
before appending another.
like this:
$("ul#optionList li").on("click", function(){
var test= $(this).attr('id');
$("ul#optionList li").removeClass('selected');
$(this).addClass('selected');
$('ul#optionList').find('.checkanswer2').remove(); // remove the other anchors
$(this).append("<a href='javascript:void(0);' class='checkanswer2' id='"+test+"'>Check Answer</a>");
$(this).children("a").remove();
});
Upvotes: 0
Reputation: 20428
Try with this
$("ul#optionList li").on("click", function(){
var test= $(this).attr('id');
$(this).siblings().removeClass('selected'); // remove other li class
$(this).addClass('selected'); // add class to clicked li
$(this).siblings().find("a").remove(); // remove other li a element
$(this).append("<a href='javascript:void(0);' class='checkanswer2' id='"+test+"'>Check Answer</a>");
});
Upvotes: 1
Reputation: 24332
Following code will solve your problem,
$("ul#optionList li").not(".selected").children("a").remove();
Upvotes: 1
Reputation: 82241
try this:
$("ul#optionList li").on("click", function(){
var test= $(this).attr('id');
$(".selected").find("a").remove();
$("ul#optionList li").removeClass('selected');
$(this).addClass('selected');
$(this).children("a").remove(); // this will caused all the buttons to be removed, not just removing the previous selected LI
$(this).append("<a href='javascript:void(0);' class='checkanswer2' id='"+test+"'>Check Answer</a>");
});
Upvotes: 0