I'm trying to delete and replace "article" tags by new one using as source a json array, but i'm always getting only the last element of the JSON array… Here how look my html structure:
<main id="main" class="site-main" role="main">
<article >
<header class="entry-header">
TEST 1
<a href="http://example.com/mdu_test/mdu_news/4996" rel="bookmark"> test</a>
<div>TAGS:<a href="http://example.com/tag/dog">dog</a></div>
</header>
</article>
<article >
<header class="entry-header">
TEST 2
<a href="http://example.com/mdu_test/mdu_news/4587" rel="bookmark"> test</a>
<div>TAGS:<a href="http://example.com/tag/cat">cat</a></div>
</header>
</article>
</main>
and here is my javascript function, using jquery to remove and replace the previous posts with the new ones.
function get_posts($params){
var $container = $('#main');
var $content = $container.find('article');
var $status = $('.ajax_tag');
var counter = 0;
… Jquery.ajax statement here …
$.each(data,function(index, post){
//$content.children().remove();
$content.empty();
console.log(index);
//$content.replaceWith('<article>' + post.title + '</article>');
//console.log(data.length);
if ( counter != data.length ) {
console.log('before : ' + counter);
$content.append('<article>' + post.title + '</br>' + '</article>');
counter += 1;
console.log('after : ' + counter);
} else {
return false;
}
});
So from here it's not clear to me how I can perform that operation.
The only way i manage to have the full list of my array was using «.append()» but without «.empty()» which then append the array content to each «article» tags.
PS: i have look at the .each(), $.each(), .map(), $.map(), for and for…in all the example and explanation i found are using the CSS "li" tag which seems to have implicite iteration where the tags «article», «div», «span» doesn't.
Hope i'm clear enough, any input would be much appreciated.
Thanks!
I finally fixed my issue with this solution, basically i'm using the jQuery
.remove()
method instead of the.empty()
one, and the it works perfectly.