luiquao
luiquao

Reputation: 1114

Dojo: how to get attr of dynamically created element

Seems like I cannot catch the click event on dynamically created elements with dojo.

This is how I create the list of links:

for(var i=0; i<items.length; i++){
     console.log( items[i].getAttribute("jid") )                    
     dojo.place("<li><a href='#' id='temp'>" + items[i].getAttribute("firstname") + "</a></li>", "log");
}

on( '#temp' ).on( 'click', function( evt ) {
    console.log( "click" );
});

Unfortunately the event doesn't get registered.

Upvotes: 0

Views: 346

Answers (1)

Thomas Upton
Thomas Upton

Reputation: 1899

Here are the docs for dojo/on; you need to pass an element, an event type, and a handler. It looks like you will need dojo/query where you're trying to use on the first time; docs are here.

It looks like you want to set up a click handler for each of your dynamically created elements. So, query for those elements and set up a click handler on each of them.

I changed your id to a class because it's not a good idea to have multiple elements with the same id, but the concept is the same. Instead of your on chain above, something like this would work:

query('.temp').forEach(function(t) {
    on(t, 'click', function(evt) {
        console.log('click', evt);
    });
});

Here's a working fiddle with some dummy items; presumably your items are slightly different.

Upvotes: 1

Related Questions