简体   繁体   中英

jquery remove/ select element from class by index

I want to remove some elements with class by the index. Let me introduce.

First, I create some divs, giving them class and an element after getting result from ajax.

$.ajax({
            type: "POST",
            url: "myphp.php",
            data: {label: label},
            success: function(result) {

                    var data ="";
                    for (i = 0; i<result.item.length; i++){
                        var data = result.item[i].data;
                        var div = $("<div class ='item'></div>");
                        var divData= "<p class ='divData' > "+ divData+"</p>";
                       }
                },
            dataType: "json",
            error: function(xhr){
                console.log("error");
            }
      });

Then, I want to remove all unnecessary divs with class = "detail" by clicking the necessary one.

$( document ).on( 'click', '.detail', function() {
    var numItems = $('.detail').length;
    for ( i = 0; i<= numItems; i++) {
        if ( i != $(this).index()){ // if the div is not selected 
             $(".detail").remove(i);//remove unnecessary div
        } 
    }
});

I do not know how to remove one element with class ="detail" by index , why $(".detail").remove(i); can not be used? It is logical, isn't it?

Try to use .not() filter at this context to ease your job,

$(document).on( 'click', '.detail', function() {
  $(".detail").not(this).remove();
});

There is no need to iterate over all the elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM