peace_love
peace_love

Reputation: 6471

How can I append a list item by click?

By click on any link on my sidebar I want to add a new list item to my breadcrump:

 <ol class="breadcrumb">
      <li>
          <a href="#">Home</a>
      </li>
    </ol> 

  $('.left-sidebar').on( 'click', 'a', function (e) {
      $(".breadcrumb").append('<li class="b_cat"><a href="#">New list item</a></li>');
  });

But each time I click, then it is adding more items to it. That is not what I need. So I had the idea to remove the item first and then add it. So only one list item is added:

 $('li').hasClass( "b_cat" ).remove();
 $(".breadcrumb").append('<li class="b_cat"><a href="#">New list item</a></li>');

But now there is no list item added. Actually nothing happens.

Upvotes: 0

Views: 134

Answers (1)

palaѕн
palaѕн

Reputation: 73966

You can remove the element with class using:

$('li.b_cat').remove();

You don't need to check if the element has a class or not because if it doesn't have that class then .remove() method will be never called.

Also, as you are adding a static item to the breadcrumb, I think you should only add once if it does not exists like:

if(!$(".breadcrumb > li.b_cat").length){
   $(".breadcrumb").append('<li class="b_cat"><a href="#">New list item</a></li>');
}

But if you adding items in the same format, but only the breadcrumb link text is changing, then you can only update that part, instead of adding the item multiple times like:

$('.left-sidebar').on('click', 'a', function(e) {
  if (!$(".breadcrumb > li.b_cat").length) {
    $(".breadcrumb").append('<li class="b_cat"><a href="#"></a></li>');
  }

  // Get clicked link text
  var currentLink = $(this).text();
  $(".breadcrumb > li.b_cat > a").text(currentLink)
});

Upvotes: 1

Related Questions