Deleting Elements and Attributes in jQuery
Continue to refer to the jQuery tutorial below by Mytour to learn various methods and techniques for deleting elements and attributes in jQuery.
1. Deleting Elements and Attributes in jQuery
2. The empty() Method in jQuery
3. The remove() Method in jQuery
4. The unwrap() Method in jQuery
5. The removeAttr() Method in jQuery
1. Deleting Elements and Attributes in jQuery
jQuery supports various methods, including empty(), remove(), unwrap(), ... to delete elements or HTML content within a document.
2. The empty() Method in jQuery
The empty() method in jQuery removes all child elements, as well as descendant elements and text content within the selected elements from the DOM.
Example: The example below illustrates how to delete all content inside elements with the class .container when clicking the button:
The output result looks like this:
Note: According to the W3C (World Wide Web Consortium) DOM technical specification, any text string within an element is considered a child node of that element.
3. The remove() Method in jQuery
The remove() method in jQuery is used to delete the selected elements from the DOM, along with any content within those elements. In addition to elements, all bound events and jQuery data related to those elements will also be removed.
Example: In the example below, it illustrates how to delete all p elements with the class .hint from the DOM after clicking the button. Elements nested inside these text paragraphs will also be deleted:
The output result looks like this:
Additionally, the remove() method in jQuery allows the use of a selector as an optional parameter, enabling users to filter the elements to be deleted.
Example: The jQuery DOM code removed in the above example can be rewritten as follows:
The output result looks like this:
Note: We can also add a selector expression as a parameter in the remove() method in jQuery, such as remove('.hint, .demo') to filter multiple elements.
4. The unwrap() Method in jQuery
The unwrap() method in jQuery is used to remove the parent element of the selected elements from the DOM.
Example: The example below will remove the parent element of p elements when clicking the button:
The output result looks like this:
5. The removeAttr() Method in jQuery
The removeAttr() method in jQuery is used to delete attributes of the selected elements.
Example: In the example below, it removes the href attribute from the a element when clicking the button:
The output result looks like this:
In this tutorial, Mytour has just guided you on how to delete elements and attributes in jQuery. Additionally, readers can explore other lessons on Mytour to learn more about callback functions in jQuery. In the next lesson, Mytour will further introduce you to how to add and remove CSS classes using jQuery.
