Luke Luke - 26 days ago 9
Javascript Question

getElementByID for Dynamically generated ID Elements

I am having an issue with getting the value of an

element of the item that is dynamically generated from the data obtained from the database. I have a query
SELECT ItemID, ItemName, ItemImageName FROM Items
. Than I have the following code that will generate
for each
for all rows returned from the database by concatenating the value of
to each ID name.

for ($i=0; $i <$numrows; $i++) {

<div> <img class="itemImage" id="Image" .$ItemID src=/images/itemImage . $itemID> $ItemID </div>
<div id= "ItemID" .$ItemID> $ItemID </div>
<div id= "ItemName" .$ItemID> $ItemName" </div>


This should return a similar result to this for an item with

<div> <img class="itemImage" id=Image002 src=/images/Image002 > </div>
<div id= ItemID002> 002 </div>
<div id= ItemName002> SomeNameOfItem002" </div>

Then I want to be able to click an image with an
and I want to get a value of
with the
. I have the following code:

var itemID = document.getElementById("ItemID").innerHTML;

$( ".itemImage" ).click(function() {
var itemID= document.getElementById("ItemID").innerHTML;

This however returns
as undefined. Any help would be greatly appreciated!

Answer Source
        <div> <img class="itemImage" id=Image001 src="/images/Image001"> </div>
        <div id=ItemID001> 001 </div>
        <div id=ItemName001> SomeNameOfItem001" </div>

        <div> <img class="itemImage" id=Image002 src="/images/Image002"> </div>
        <div id=ItemID002> 002 </div>
        <div id=ItemName002> SomeNameOfItem002" </div>

        <div> <img class="itemImage" id=Image003 src="/images/Image003"> </div>
        <div id=ItemID003> 003 </div>
        <div id=ItemName003> SomeNameOfItem003"> </div>

            $(document).ready(function () {
                $(".itemImage").click(function () {
                    var imgID = $(this).prop('id').replace("Image", "");
                    // you can directly use value imgID variable if its same. or you 
                    //can use from ItemID inner html
                    var yourValue = $("#ItemID" + imgID).html();