I've got this code which is working ok. The new piece of data is coming in ok but when the number of p's gets to 3, nothing happens. The last item doesnt get removed and no new items get appended.
Any ideas?
setInterval(function() {
$.post(
'json.php',
function(data){
$('#tweetBox').append('<p>' + data + '</p>');
var list = $('#tweetBox p').length;
if (list > 3){
$('#tweetBox p:last-child').remove();
}
}
);
}, 5000);
:last-child will not work if the element is not the VERY LAST element. In addition to Harry's answer, I think it's crucial to add/emphasize that :last-child will not work if the element is not the VERY LAST element in a container.
Pseudo-selectors like :last-child or nth-child or nth-of-type only select based on elements not classes or attributes. Either something is the last-child or it isn't. If it's the last element in a parent it will be selected. So, in your case, it's testing for it to meet all the conditions.
The :nth-last-child() pseudo-class represents an element that has an+b siblings after it in the document tree, for any positive integer or zero value of n, and has a parent element.
:not(:last-child) The :last-child selector selects the last child. Combining these two above selector to excludes the last children (inner-div) of every parent div from the selection.
The last item doesn't get removed and no new items get appended.
That indicates that the new item gets appended but removed instantly. You want to reverse the order:
var list = $('#tweetBox p').length;
if (list === 3){
$('#tweetBox p:last-child').remove();
}
$('#tweetBox').append('<p>' + data + '</p>');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With