How to get ID by clicking on a Dynamically added element

4

I'm getting inside a div new elements via PHP using XMLHttpRequest . So far so good, I get the elements and it displays everything right, but I'm not able to get the ID of these new elements using the Click event.

Ex:

<div id="res"> 
    <li class="new" id="50">Novo Elemento</li> 
    <!-- aqui é inserido o novo elemento via XMLHttpRequest (do PHP). -->
</div>

In my JS I do (but it does not work):

var el = document.getElementsByClassName('new');
for(var i = 0; i < el.length; i++){
    el[i].addEventListener('click', function(){
       alert( this.getAttribute('id') ); //aqui seria o ID que to precisando. :(
    }, false);
}

I need something similar to the code below, but in JavaScript (Pure) without using JQuery:

$('#res').on('click', 'li.new', function(){
    alert( $(this).attr('id') ); //aqui retorna certo...
});

I searched for Google but found nothing.

How could I do this?

    
asked by anonymous 21.10.2014 / 19:53

1 answer

2

You can make a delegator of your own.

If there is only li inside the div then e.target.id should give you what you need, otherwise you have to check e.target.tagName.toLowerCase() == 'li' first. You can also add a condition to check the class. Using classList.contains or className.indexOf('new') != -1

For example:

var res = document.getElementById('res');
res.addEventListener('click', function(e){
       var elemento = e.target;
       if (elemento.tagName.toLowerCase() == 'li' && elemento.classList.contains('new')) alert(elemento.id);
       else return false;
}, false);

Example: link

    
21.10.2014 / 19:59