开发者

replace a divs contents with the last entry

开发者 https://www.devze.com 2023-01-18 14:21 出处:网络
I have a div with a bunch of list items in it. I just want to remove all the contents inside except for the last list item. Is it p开发者_如何学Goossible to use $(this) in reference to a div id withou

I have a div with a bunch of list items in it. I just want to remove all the contents inside except for the last list item. Is it p开发者_如何学Goossible to use $(this) in reference to a div id without putting it inside some sort of click function? Something like this? (I know its wrong)

 $('div[id='+id+']').html($(this).(".list-item:last"));

If not, would I need to make a function and then call it?

$('div[id='+id+']').function(){
 $(this).html($(".list-item:last"));
}


This should work for what you require, I think:

$('#elementId').children().not(':last-child').remove();

Demo at: JS Bin.


One way to do this is to use a selector to get the last list item, then remove its siblings. Something like this:

$('div li:last-child').siblings().remove();

Last child: http://api.jquery.com/last-child-selector/

Siblings: http://api.jquery.com/siblings/

Remove: http://api.jquery.com/remove/

0

精彩评论

暂无评论...
验证码 换一张
取 消