88willr
88willr

Reputation: 148

Get .length of NEW dynamically added div

6 items are added onload using ajax. Each click, 6 items are being appended. I want to hide #load-more button if newly added items are less than 6.

How to find the count of newly added items?

I use .length but all items are being counted. Thanks for your help.

var max = 6;
var NewItems = $(".items").length;
if (NewItems > max) {
   $("#load-more").hide();
  } else {
   $("#load-more").show();
}

var max = 6;
var start = 1;
var winloc = window.location;
$(window).bind('hashchange', function() {
if (winloc.hash === "" || winloc.hash === "#home") {
homeurl = `https://mailliw88.blogspot.com/feeds/posts/default?start-index=${start}&max-results=${max}&alt=json-in-script`;
loadList(homeurl);
}
}).trigger('hashchange')

function more() {
  start += max;
  loadList(`https://mailliw88.blogspot.com/feeds/posts/default?start-index=${start}&max-results=${max}&alt=json-in-script`);
}

function loadList(url) {
  $.ajax({
    url: url,
    type: 'get',
    dataType: "jsonp",
    success: function(data) {
      if (data.feed.entry) {
        datas = data.feed.entry;
        var entry = data.feed.entry;
        for (var i = 0; i < entry.length; i++) {
          postTitle = entry[i].title.$t;
          items = '<div class="items"><h2><a href="#">' + postTitle + '</a></h2></div>';
          document.getElementById('showlists').innerHTML += items;
        }
      }
      var newItems = $(".items").length;
      if (newItems > max) {
        $("#load-more").hide();
      } else {
        $("#load-more").show();
      }
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='showlists'></div>
<div id='load-more' onclick="more()">
load more
</div>

Upvotes: 0

Views: 484

Answers (2)

Colin G
Colin G

Reputation: 165

Change:

  var newItems = $(".items").length;
  if (newItems > max) {

To:

  if (data.feed.entry.length < 6)

The variable "max" will be out of scope for your "success" method since it's defined outside of it and is an integer type, so you will need to either directly add it, or use an object, like:

  var max = {entries: 6};
  ...
  if (data.feed.entry.length < max.entries)

Upvotes: 1

Zachiah
Zachiah

Reputation: 2627

You could add data attributes to the new items with an incrementing id so the final html would look like

<div data-load="1"></div>
<div data-load="1"></div>
...
<div data-load="2"></div>
...

and then in you're js

$(`div[data-load="${Math.max(...$('div').map(item => parseInt(item.attr("data-load"))))}"`)

would get all the latest ajax elements

Upvotes: 0

Related Questions