user5283721
user5283721

Reputation: 615

Appending a div to a div created dynamically

I am iterating an array and creating a div on the fly as follows:

   $.each(item,function(k,item2) {
     html = '<td><div id="test">'+item2.Name +'</div></td>'

     //For just testing purpose , I am adding a div dynamically as:
     $("#test").append("<div class='test class'></div>");
   });

But finally when I browse the html page , the new div with class='test class' is not to be found at all. Is there anything which I am missing?

Edit : In the html tag "html", there are multiple divs , and I want to append to a particular div by id

Not exactly sure what the problem is : but after the html has been created , $("#test").append("<div class='test class'></div>"); works but appending using $(html).find() doesnt

Upvotes: 0

Views: 121

Answers (2)

GS-Magento
GS-Magento

Reputation: 328

You are not creating the element with id "test" dynamically, you have just assigned in variable. please try the below code

$.each(item,function(k,item2) {
     html = '<td><div id="test">'+item2.Name +'</div></td>';
     $('any existing element class/id').html(html);
     //For just testing purpose , I am adding a div dynamically as:
     $("#test").append("<div class='test class'></div>");
});

Upvotes: 0

Rayon
Rayon

Reputation: 36609

As element is not appended in the DOM, you can not access it using $ selector. You can use html variable holding element in the form of string, content will not be the document but you can access #test element after wrapping it with $

 $.each(item, function(k, item2) {
   var html = '<td><div id="test">' + item2.Name + '</div></td>';
   $(html).find('#test').append("<div class='test class'></div>");
 });

Upvotes: 2

Related Questions