How to get ID by clicking on a dynamically added Element

Asked

Viewed 87 times

4

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

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 do (but 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, only in Javascript(Pure) without using Jquery:

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

I Googled but I found nothing.

How could I do that?

1 answer

2


You can make your own delegator.

If there’s only li inside the div then the e.target.id should give you what you need, or you’ll have to check e.target.tagName.toLowerCase() == 'li' first. You can 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: http://jsfiddle.net/fz6368a9/

  • 1

    If I understand correctly, #res is dynamically insightful

  • 1

    @bfavaretto if #res is also dynamic then Event Handler can be added to the window: http://jsfiddle.net/9374tgbf/

  • 2

    @Sergio worked out that’s just what I needed. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.