CHHU
CHHU

Reputation: 71

Javascript 'click' onto wrong element when dynamically generating elements

I am adding some elements dynamically to a page when making this chrome extension. It is a list added like this

 var result = document.createElement("UL");
 var checkoutArea = document.getElementById("shipping");
 result.setAttribute("id", "resList");
 if (document.getElementById("resList") === null) {
   checkoutArea.appendChild(result);
 }

I am also adding <'li'> child to it later. But when I am trying to add onclick function to each item, it does not work. I checked when I click on the item dynamically generated, and it seems that those items are not clicked, as this gives wrong results:

document.addEventListener('click', function(e) {
  e = e || window.event;
  var target = e.target || e.srcElement,
  text = target.textContent || text.innerText;
  console.log(text);
}, false);

a screenshot of the DOM of dynamically generated list

Also when I 'inspect' on that 'home' item, chrome is giving me that highlighted element, which is the 'save & continue' button besides. I am thinking there's an overlap, so how should add any 'onclick' function to those items?? Great thanks in advance.

Upvotes: 2

Views: 295

Answers (1)

Mario
Mario

Reputation: 4998

You probably need to try the Event delegation pattern. The idea is that if we have a lot of elements handled in a similar way, then instead of assigning a handler to each of them – we put a single handler on their common ancestor.

Read about it on this link: http://javascript.info/event-delegation

I managed to understand Event delegation thanks to video 15 that has the name LocalStorage and Event Delegation in the course javascript30 of Wes Bos. The course is free and worthwhile. I hope this information serves you

Upvotes: 1

Related Questions