jQuery 메서드 비교 hide, detach, empty, remove

카테고리 IT/코딩 Javascript

무찌마, 댓글

초고 2021. 8. 15.

hide()

 

Hides the matched elements.

Sets the matched elements' CSS display property to none.


detach()

 

Removes the set of matched elements from the DOM.

Removes all child elements with the selected elements.

Keeps all data and event handlers of the removed elements.

Preferred to remove elements but to keep copy of the removed elements for reuse at a later time.


How to reinsert the detached element into the DOM

 

var span = $('span').detach();
...
span.appendTo('body');

 

$("#three").each(function(){
  $(this).detach().insertAfter("#one");
});

 

<body>
how are
<button>Attach/detach paragraphs</button>
<script>
	window.onload = function() {
		$( "p" ).click(function() {
  			$( this ).toggleClass( "off" );
		});
		var p;
		$( "button" ).click(function() {
  			if ( p ) {
    			p.appendTo( "body" );
    			p = null;
  			} else {
    			p = $( "p" ).detach();
  			}
		});
	};
</script>
<p>Hello</p>
<p>You?</p>
</body>

empty()

 

Does not remove the set of matched elements itself from the DOM.

Removes any text within the set of elements.

Removes all child nodes of the set of matched elements from the DOM.

Removes all content and child elements from the selected element.


remove()

 

empty() + remove the set of matched elements itself

 

Removes the set of matched elements itself from the DOM.

Removes any text within the set of elements.

Removes all child nodes of the set of matched elements from the DOM.

All data and events related with the elements are removed.

 

In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use 'detach()' instead.

댓글