I am trying to get an dynamically created element using a jQuery selector but it is returning an empty array.
The first thing I am doing is grabbing an empty div:
var packDiv = document.getElementById('templates');
packDiv.innerHTML = "";
then adding items to it in a loop:
packDiv.innerHTML = packDiv.innerHTML + "<img id='" + thumbName + "' src='thumbs/" + thumbName + "'/>";
after the loop finishes I try to select an item using:
console.log($("#"+thumbName));
and it returns the empty array. All the things I search on show to use .on but all the examples show that is to set event handlers.
My question is how do I format a selector for dynamically created elements?
Assuming
thumbNameis a file name, for examplefoo.jpg, it would not be parsed by jQuery as you would expect..jpgpart of the name is treated as a class name, and since you are not providing this class name for that element, jQuery returns an empty array – it does not find anything matching your selector. You are actually searching for an element with idfooand class namejpg.The way I would go with this is something along these lines: