Removing specific element from a list with JQuery

前端 未结 4 606
迷失自我
迷失自我 2021-02-14 10:35

i have a dynamic list, which looks like this:

  • Text1
  • Text2<
相关标签:
4条回答
  • 2021-02-14 10:40

    You probably had some silly mistake, it should work:

    $('#buttonId').click(function(){
            $('#tl_2').remove();
        });
    

    Note that there is no need to "find" for element by id. id is unique.

    $('li').find('tl_1').remove();  // And you were missing the # anyway...
    

    Make sure you have only one element for each id. id is like id... You can have only one with the same value.

    Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.

    0 讨论(0)
  • 2021-02-14 10:42

    You probably have more than one element with the same ID.

    You don't have to use ID at all in case you want to remove them by index you can use the .eq() method:

    $("#btnRemove").click(function() {
        $("#myList li").eq(1).remove();
    });
    

    This will remove the second list item each click.

    Live test case.

    0 讨论(0)
  • 2021-02-14 10:43

    You must have an error somewhere else, because what you have just works.

    Please check your error console.

    Although your second example should be:

    $('ul').find('#tl_2').remove(); // but this isn't really needed since we are selecting by id. So just go for the first example which is faster.
    
    0 讨论(0)
  • 2021-02-14 10:56

    I think you are not showing us some part of your code as i suspect you are trying to generate that id dynamically, meaning u set it dynamically as well. you have to make sure that there is no 'space' character within the id which will likely mess thing up...

    $('#tl_2').remove();
    

    Works according to jquery documentation. it worked for me.

    0 讨论(0)
提交回复
热议问题