How to delete the first child of an element but referenced by $(this) in Jquery?

南笙酒味 提交于 2019-12-12 07:46:32

问题


The scenario is I have two divs: one is where I select items (divResults) and it goes to the next div (divSelectedContacts). When I select it I place a tick mark next to it. What I want to do is when I select it again I want to remove the tick mark and also remove the element from divSelectedContacts.

Here is the code:

$("#divResults li").click(function()
{
    if ($(this).find('span').size() == 1)
    {
        var copyElement = $(this).children().clone();
        $(this).children().prepend("<span class='ui-icon ui-icon-check checked' style='float:left'></span>");
        $("#divSelectedContacts").append(copyElement);
    } else
    {
        var deleteElement = $(this).find('span'); //here is the problem how to find the first span and delete it
        $(deleteElement).remove();
        var copyElement = $(this).children().clone();//get the child element
        $("#divSelectedContacts").find(copyElement).remove(); //remove that element by finding it
    }
});

I don't know how to select the first span in a li using $(this). Any help is much appreciated.


回答1:


Several ways:

$(this).find('span:first');

$(this).find(':first-child');

$(this).find('span').eq(0);

Note that you don't need to use $(deleteElement) as deleteElement is already a jQuery object. So you can do it like this:

$(this).find('span:first').remove();



回答2:


To get the first child of $(this) use this:

$(this).find(":first-child");



回答3:


or you could just throw it all into the selector...

$('span:first', this);


来源:https://stackoverflow.com/questions/2592891/how-to-delete-the-first-child-of-an-element-but-referenced-by-this-in-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!