Bryan Williams
Bryan Williams

Reputation: 693

jQuery selector after dynamically created element

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?

Upvotes: 1

Views: 250

Answers (1)

pckill
pckill

Reputation: 3759

Assuming thumbName is a file name, for example foo.jpg, it would not be parsed by jQuery as you would expect. .jpg part 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 id foo and class name jpg.

The way I would go with this is something along these lines:

var packDiv = $('#templates');
packDiv.empty();

//inside a loop
packDiv.append("<img class='" + thumbName.replace(/\./g,'') + "' src='thumbs/" + thumbName + "'/>");

console.log($("."+thumbName.replace(/\./g,'')));

Upvotes: 2

Related Questions