Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
jQuery 2.0 Development Cookbook

You're reading from   jQuery 2.0 Development Cookbook As a web developer, you can benefit greatly from this book - whatever your skill level. Learn how to build dynamic modern websites using jQuery. Packed with recipes, it will quickly take you from beginner to expert.

Arrow left icon
Product type Paperback
Published in Feb 2014
Publisher Packt
ISBN-13 9781783280896
Length 410 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Leon Revill Leon Revill
Author Profile Icon Leon Revill
Leon Revill
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Document Object Model Manipulation FREE CHAPTER 2. Interacting with the User by Making Use of jQuery Events 3. Loading and Manipulating Dynamic Content with AJAX and JSON 4. Adding Attractive Visuals with jQuery Effects 5. Form Handling 6. User Interface 7. User Interface Animation 8. Understanding Plugin Development 9. jQuery UI 10. Working with jQuery Mobile Index

Re-using DOM elements

When using jQuery to dynamically create elements such as list items, divisions, and input, it can be useful to be able to re-use these elements without having to rewrite them within JavaScript. Instead, it may be beneficial to copy the elements and just modify the sections you wish to change.

Getting ready

Using the text editor of your choice, create a blank HTML document named recipe-12.html, which is within a location that has easy access to the latest version of jQuery.

How to do it…

Learn how to re-use DOM elements by performing each of the following recipe steps:

  1. Within the recipe-12.html page you have just created, add the following HTML, CSS, and JavaScript code:
    <!DOCTYPE html>
    <html>
    <head>
       <title>Reusing DOM elements</title>
       <style type="text/css">
          .one {
             background-color: #CCC;
             color: #333;
          }
          .two {
             background-color: lawngreen;
             color: white;
          }
          .three {
             background-color: darkgreen;
             color: white;
          }
          .four {
             background-color: black;
             color: #666;
          }
          .dinosaur {
             background-color: darkred;
             color: red;
          }
       </style>
       <script src="jquery.min.js"></script>
       <script>
          var animals = [
             {
                id: 1,
                name: 'Dog',
                type: 'Mammal',
                class: 'one'
             },
             {
                id: 2,
                name: 'Cat',
                type: 'Mammal',
                class: 'one'
             },
             {
                id: 3,
                name: 'Goat',
                type: 'Mammal',
                class: 'one'
             },
             {
                id: 4,
                name: 'Lizard',
                type: 'Reptile',
                class: 'two'
             },
             {
                id: 5,
                name: 'Frog',
                type: 'Amphibian',
                class: 'three'
             },
             {
                id: 6,
                name: 'Spider',
                type: 'Arachnid',
                class: 'four'
             }
          ];
          $(function(){
    
          });
       </script>
    </head>
    <body>
    <ul id="animal-list">
       <li class='dinosaur'><strong><span class='name'>T-Rex</span></strong> <span class='type'>Dinosaur</span></li>
    </ul>
    </body>
    </html>
  2. Within the HTML page you created from the preceding code, add the following JavaScript within $(function(){});:
    $.each(animals, function(index, obj){
    //Clone the first element in the animal list
    var listTemplate = $('#animal-list li').first().clone();
    //Change its name to match this objects name
    listTemplate.find('.name').html(obj.name);
    //Changes its type to match this objects type
    listTemplate.find('.type').html(obj.type);
    //Remove all its current classes
    listTemplate.removeClass();
    //Add the class from this object
    listTemplate.addClass(obj.class);
    //Append the modified element to the end of the list
    $('#animal-list').append(listTemplate);
    });
  3. If you open your newly created web page within a browser, you should be provided with a populated list element that matches the objects within the JavaScript array animals.

How it works…

By using jQuery's $.each() method, we are able to iterate through each of the objects within the JavaScript animals array. Then, for each of the JavaScript objects, we clone the first element in the unordered list using $('#animal-list li').first().clone(); and store it within the listTemplate variable. This variable now holds a copy of the first list element within the unordered list #animal-list. We can now manipulate this element as we would do with any other DOM element. We are able to use jQuery's find() function to locate the span elements with the .name and .type class names. We can then alter their content to match the current object's name and type values. Next, we remove the previous styles on the cloned element with removeClass() (not providing an argument will remove all current classes without having to specify each one of them), and add the style that is specified within the JavaScript object using the addClass() function that jQuery provides us with. Finally, we can append the modified HTML element to the end of the list using append().

See also

  • Removing DOM elements
  • Creating DOM elements
You have been reading a chapter from
jQuery 2.0 Development Cookbook
Published in: Feb 2014
Publisher: Packt
ISBN-13: 9781783280896
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image