Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .remove() and last-child not working as expected

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);
like image 753
benhowdle89 Avatar asked May 02 '11 15:05

benhowdle89


People also ask

Why is my last child not working?

: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.

Why is last child not working CSS?

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.

What is nth last child?

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.

How do you use not your last child in SCSS?

: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.


1 Answers

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>');
like image 150
Felix Kling Avatar answered Nov 15 '22 09:11

Felix Kling