Differences between detach(), hide() and remove() - jQuery

后端 未结 5 2060
忘了有多久
忘了有多久 2020-11-28 02:52

What is the functional difference between these three jQuery methods:

  • detach()
  • hide()
  • remove()
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 03:15

    In jQuery, there are three methods for removing elements from the DOM. These three methods are .empty(), .remove(), and .detach(). All these methods are used for removing elements from the DOM, but they all are different.

    .hide()

    Hide the matched elements. With no parameters, the .hide() method is the simplest way to hide an HTML element:

    $(".box").hide();
    

    .empty()

    The .empty() method removes all child nodes and content from the selected elements. This method does not remove the element itself, or its attributes.

    Note

    The .empty() method does not accept any argument to avoid memory leaks. jQuery removes other constructs, such as data and event handlers, from the child elements before removing the elements themselves.

    Example

    Hai
    good evening

    This will result in a DOM structure with the Hai text deleted:

    good evening

    If we had any number of nested elements inside

    , they would be removed too.

    .remove()

    The .remove() method removes the selected elements, including all text and child nodes. This method also removes the data and events of the selected elements.

    Note

    Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to this, all bound events and jQuery data associated with the elements are removed.

    EXAMPLE

    Consider the following html:

    Hai
    good evening

    This will result in a DOM structure with the

    element deleted:

    good evening

    If we had any number of nested elements inside

    , they would be removed too. Other jQuery constructs, such as data or event handlers, are erased as well.

    .detach()

    The .detach() method removes the selected elements, including all text and child nodes. However, it keeps data and events. This method also keeps a copy of the removed elements, which allows them to be reinserted at a later time.

    Note

    The .detach() method is useful when removed elements are to be reinserted into the DOM at a later time.

    Example

    
    
    
    
    
    
    
    

    Hai!

    Good

    Afternoo

    For more info, visit: http://www.scriptcafe.in/2014/03/what-is-difference-between-jquery_15.html

提交回复
热议问题