Using jQuery to add a div, add more elements to the new div without id

I need to use jQuery to add a div with the class 'address-line' to another element with the id 'add-results', and then add several elements to the newly created div. Then repeat this for each element of the object.

Here is what I am trying to summarize:

<div id="add-results"> <div class="address-line"> <h2>title 1</h2> <p>desc 1</p> <img src="thing1.png" /> </div> <div class="address-line"> <h2>title 2</h2> <p>desc 2</p> <img src="thing2.png" /> </div> <!-- etc repeated on a loop --> </div> 

Here is one of many things I've tried (chdata is an object, chvalue will store data):

 $.each(chdata, function(name, chvalue) { $('#add-results').append('<div class="address-line">'); $('#add-results').append('<h2>'+chvalue['title']+'</h2>'); // etc.. adding paragraph, an image, some links. }); 

.. but, of course, this leads to the following:

 <div id="add-results"> <div class="address-line"></div> <h2>title 1</h2> <p>desc 1</p> <img src="thing1.png" /> <div class="address-line"></div> <h2>title 2</h2> <p>desc 2</p> <img src="thing2.png" /> </div> 

I also tried using:

 $('#add-results').append('<div class="address-line">') .append('<h2>'+chvalue['title']+'</h2>'); 

.. but the same result. How can I achieve this?

+4
source share
2 answers

You can use the .appendTo method.

 $.each(chdata, function(name, chvalue) { $('<div class="address-line">') .append('<h2>'+chvalue['title']+'</h2>') // etc.. adding paragraph, an image, some links. .appendTo('#add-results'); // at last appendTo the #add-results }); 
+5
source

Save the new div and link, instead of reusing append. .append will return the orignal element that you are adding, not the added element. Try something like this:

 var newdiv = $('<div>',{'class':'address-line'}); newdiv.append(...); $('#add-results').append(newdiv); 

Compiled (I prefer to use jQuery and the .text method instead of passing the raw HTML in case this value contains something that can ruin the HTML, but for each of it):

 $.each(chdata, function(name, chvalue) { // Create and store your new div var div = $('<div>',{'class':'address-line'}); // append the new elements to it $('<h2>').text(chvalue['title']).appendTo(div); $('<p>').text(chvalue['description']).appendTo(div); $('<img>',{'src':chvalue['image']}).appendTo(div); // insert that new div into #add-results div.appendTo('#add-results'); }); 
+2
source

Source: https://habr.com/ru/post/1438907/


All Articles