Detach and Attach DOM Elements: jQuery Array


Video tutorial illustrates the use of jQuery’s special type of variable called array.

Array variable stores multiple data with single name with different index. Indexing starts from zero in jQuery.
This helps in storing and retrieving easily using some conditional looping.

In this example, we take a unordered list with some list items which has two type of class veg and nonveg.
Another ordered list, with only 1 list item.
Two buttons. One to detach the items from unordered list, which has a class called veg.
Another button, to attach it to the ordered list.

HTML code
index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<html>
<head><title>Detach and Attach DOM Elements: jQuery Arrays!</title></head>
<body>
 
<ul>
<li class="veg">Rice</li>
<li class="nonveg">Fish</li>
<li class="nonveg">Chicken</li>
<li class="veg">Veg Pizza</li>
</ul>
 
<ol>
<li class="veg">Veg Paneer</li>
</ol>
 
<button id="remove">Remove</button>
<button id="attach">Attach</button>
 
<script src="script/jquery-1.8.1.min.js" type="text/javascript"></script>
<script src="script/my_script.js" type="text/javascript"></script>
</body>
</html>

Here you have 1 unordered list. 1 Ordered list and 2 buttons.

jQuery code
my_script.js

1
2
3
4
5
6
7
8
9
10
11
$(document).ready( function() {
 
 $("#remove").click( function() {
   $store = $("ul li.veg").detach();
 });
 
 $("#attach").click( function() {
   $("ol li").after($store);
 });
 
});

Once the user clicks on the button with the id remove, we detach the list items with class veg from the unordered list and store it inside the special jQuery array variable.
Next, when the user clicks on the button with the id of attach, we attach it to the ordered list using append(), after(), before() methods of jQuery, by passing the array variable to these methods.

Video Tutorial: Detach and Attach DOM Elements: jQuery Array


[youtube https://www.youtube.com/watch?v=UHSrD8j5Czc]

YouTube Link: https://www.youtube.com/watch?v=UHSrD8j5Czc [Watch the Video In Full Screen.]



Unlike remove() method, detach() doesn’t delete the DOM structure or the HTML elements.

Related Read:
jQuery Methods and CSS: Restaurant Application

Note: You could even use the normal javascript arrays in jQuery too. We shall look at it in the future videos.

Leave a Reply

Your email address will not be published. Required fields are marked *