Yassine XM
Yassine XM

Reputation: 78

how to add event listener to appened content on javascript

i have created my own jquery because i need only these 4 functions,

everything is working well until i click append.

i tried document.getElementsByTag because it returns live htmlcollection but didnt work

function $(s)
{
 var el;
 if (s instanceof HTMLElement) { el = [s]; } else { el = document.querySelectorAll(s); }
 const obj = 
 {
  elm : el,
  show : function() { var i = obj.elm.length; while (i--) { obj.elm[i].style.display = ""; } },
  hide : function() { var i = obj.elm.length; while (i--) { obj.elm[i].style.display = "none"; } },
  on : function(ev,cb) { var i = obj.elm.length; while(i--) { obj.elm[i].addEventListener(ev,cb); } },
  append : function(cn) { var i = obj.elm.length; while(i--) { obj.elm[i].innerHTML += cn; } }
 }
 return obj
}
<ul>
 <li>Click to hide</li>
 <li>Click to hide</li>
 <li>Click to hide</li>
 <li>Click to hide</li>
</ul>
<button id="sh">Show</button>
<button id="ap">Append</button>

<script>
 document.addEventListener("DOMContentLoaded", function() {

  $("li").on("click", function() {
   $("li").hide();
   
  });
  $("#sh").on("click", function() {
   $("li").show();
  });

  $("#ap").on("click", function() {
   $("ul").append("<li>X<li/>");
  });
 });
</script>

Upvotes: 0

Views: 74

Answers (1)

arieljuod
arieljuod

Reputation: 15838

I would change your code a bit (innerHTML += is a bad practice, it breaks the current listeners).

First change your click listener:

  $("#ap").on("click", function() {
    const li = document.createElement('li');
    li.innerText = 'X';
    // add the event listeners to the li element
    li.addEventListener(...)
    // append it
    $("ul").append(li);
  });

Now change this obj.elm[i].innerHTML += cn; to obj.elm[i].insertAdjacentElement('beforend', cn). Notice that in this version, cn is an HTML element and NOT a string, and it's using insertAdjacentElement instead of innerHTML += so you don't lose the previous event listeners.

Upvotes: 1

Related Questions