Cannot get dynamically created div id

I created a dynamic div along with a table ... I want that when I click on the image inside the div, it will give out the identifier of the div that I clicked on ... the code is below, Please mark where the error is ...!? In the warning window, I cannot get the div id

The following code creates a div

function create_newGrid() {
    //create div for corresponding table
    var tableDiv = $('<div/>').attr({ "id": "settingsDiv-tab" + nooftables });
    var divImage = $('<img/>').attr({ "src": "settingsImage/settings.png", "onclick": "openTableSettings(this);" })
    $(tableDiv).append(divImage);
    // append grid to designer
    $(document.getElementById("center")).append(tableDiv);
    $(document.getElementById("center")).append(table);
}

the next is the function that is executed when an image is clicked on an element

function openTableSettings(div) {
    alert($(div).attr("id"));

}
+3
source share
4 answers

You pass the link to img to openTableSettings(). Use .closest()to get div:

function openTableSettings(img) { 
    alert($(img).closest("div").attr("id")); 
} 
+1
source

, onclick , . , div , , . ( , )

//create div for corresponding table
var tableDiv = $('<div/>').attr({ "id": "settingsDiv-tab", "onclick": "alert($(this).attr('id'));"});
var divImage = $('<p>this is a big bunch of text</p>');
tableDiv.append(divImage);
$(document.body).append(tableDiv);
+1

Maybe better if you do

var divImage = $('<img/>').attr({ "src": "settingsImage/settings.png", class: "clickable"});

and then

$(window).on('click', 'img.clickable', function(){
   alert(this.id);
});

(this assumes jQuery> = 1.7)

0
source

try the following:

$("div > img").click(function() { 
    id = $(this).parent("div").attr("id");
    alert(id);    
})
0
source

All Articles