Reputation: 12747
I'm creating an element in javascript, giving it an ID, and then accessing it via jQuery. I thought it would be simple enough but for some reason this is not working:
var img = document.createElement('img');
img.id = "uploadedimg";
if($('#uploadedimg').length==0)
alert("it's not there");
else
alert("it is there!");
The alert I get is "It's not there". I know how to create an element in jQuery but I want to know what's wrong with this code.
Upvotes: 2
Views: 1190
Reputation: 16190
You have to append the element before looking for it in the DOM using jQuery.
Use the appendChild
method to do that. For example:
document.body.appendChild(img);
And after that, access it with jQuery.
The other way would be to convert the element to a jQuery object directly, like this: $(img)
. After that you can use jQuery's usual methods on it.
Upvotes: 5