How to clear all
s’ contents inside a parent
?

前端 未结 14 1873
面向向阳花
面向向阳花 2020-12-07 10:10

I have a div

which has several child
s.

Example:

<
相关标签:
14条回答
  • 2020-12-07 10:46

    jQuery recommend you use ".empty()",".remove()",".detach()"

    if you needed delete all element in element, use this code :

    $('#target_id').empty();
    

    if you needed delete all element, Use this code:

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

    i and jQuery group not recommend for use SET FUNCTION like .html() .attr() .text() , what is that? it's IF YOU WANT TO SET ANYTHING YOU NEED

    ref :https://learn.jquery.com/using-jquery-core/manipulating-elements/

    0 讨论(0)
  • 2020-12-07 10:47

    jQuery's empty() function does just that:

    $('#masterdiv').empty();
    

    clears the master div.

    $('#masterdiv div').empty();
    

    clears all the child divs, but leaves the master intact.

    0 讨论(0)
  • 2020-12-07 10:51

    Use jQuery's CSS selector syntax to select all div elements inside the element with id masterdiv. Then call empty() to clear the contents.

    $('#masterdiv div').empty();
    

    Using text('') or html('') will cause some string parsing to take place, which generally is a bad idea when working with the DOM. Try and use DOM manipulation methods that do not involve string representations of DOM objects wherever possible.

    0 讨论(0)
  • 2020-12-07 10:54

    When you are appending data into div by id using any service or database, first try it empty, like this:

    var json = jsonParse(data.d);
    $('#divname').empty();
    
    0 讨论(0)
  • 2020-12-07 10:55

    The better way is :

     $( ".masterdiv" ).empty();
    
    0 讨论(0)
  • 2020-12-07 10:58

    If all the divs inside that masterdiv needs to be cleared, it this.

    $('#masterdiv div').html('');
    

    else, you need to iterate on all the div children of #masterdiv, and check if the id starts with childdiv.

    $('#masterdiv div').each(
        function(element){
            if(element.attr('id').substr(0, 8) == "childdiv")
            {
                element.html('');
            }
        }
     );
    
    0 讨论(0)
提交回复
热议问题