Search code examples
javascriptjquerycreateelement

How to add an element if a div is clicked but remove the same element from the others?


I have an onclick function that add an element if a div is clicked

function clickOnADivToCreateLi(element) {
  var div = $(element);
  var i = document.createElement("i");
  $(i).addClass("fas fa-check-circle clicked");
  div.append(i);
}

But when I click on another div with the same class, I have two div with the same <i> and if I click again that div will have 2 <i>s

How do add the <i> but at the same time remove it from the others?


Solution

  • Select the i elements matching the classes you assigned to it and call remove() before creating the new instance.

    Also note that your code can be made much more succinct:

    function clickOnADivToCreateLi(element) {
      $('i.fas.fa-check-circle.clicked').remove();
      $(element).append('<i class="fas fa-check-circle clicked" />');
    }