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

Creating DOM elements

To create rich and interactive user interfaces, we need to be able to dynamically add DOM elements to a web page. Elements may need to be added to a web page based on user interaction or another event such as page load.

Getting ready

For this recipe, you are going to need another blank HTML file. Create a new HTML file named recipe-3.html within the same directory as the one used for the previous recipe's files.

How to do it…

Learn how to create DOM elements with jQuery by performing the following steps:

  1. Add the following HTML code to your recipe-3.html file in order to create a basic HTML page with an unordered list and include the jQuery library:
    <!DOCTYPE html>
    <html>
    <head>
       <title>Creating DOM elements</title>
       <script src="jquery.min.js"></script>
       <script></script>
    </head>
    <body>
    <div id="container">
       <ul id="myList">
          <li>List Item 1</li>
          <li>List Item 2</li>
          <li>List Item 3</li>
       </ul>
    </div>
    </body>
    </html>
  2. Add the following JavaScript within the script tags in the head of the HTML document. The following JavaScript code will add two buttons to the DOM after the #myList element utilizes jQuery's after() and insertAfter() functions:
    $(function(){
       $('#myList').after("<button>Button 1</button>");
       $('<button>Button 2</button>').insertAfter("#myList");
    });

How it works…

To dynamically add DOM elements to any part of the document, we can use the append(), addAfter(), after(), addBefore(), and before()functions of jQuery. The functions after() and insertAfter() essentially perform the same action; the difference lies in the order in which the expressions are specified. This is the same for insertBefore() and before().

Based on the HTML file in the How to do it... section, the following JavaScript will add two button elements after the unordered list element:

$(function(){
   $('#myList').after("<button>Button 1</button>");
   $('<button>Button 2</button>').insertAfter("#myList");
});

Once the preceding JavaScript has been executed, the HTML rendered in the browser should be modified as follows:

<!DOCTYPE html>
<html>
<head>
   <title> Creating DOM elements</title>
   </head>
<body>
<div id="container">
   <ul id="myList">
      <li>List Item 1</li>
      <li>List Item 2</li>
      <li>List Item 3</li>
   </ul>
      <button>Button 2</button>
      <button>Button 1</button>
</div>
</body>
</html>

Note that even though the second button was added last, it is first in the HTML. This is because we have specified that the button should be inserted after the unordered list element. Both .before() and .insertBefore() jQuery methods work exactly in the same way, except that the button elements would be above the unordered list element.

A common requirement of dynamic web pages and web applications is to be able to add new items to a list. This is best achieved using the .append() function:

$(function(){
   $('#myList').append("<li>List Item 4</li>");
});

This JavaScript will add the new list item with the text List Item 4 to the bottom of the #myList unordered list element. Alternatively, the prepend() function could be used to insert the list item at the top of the list.

There's more…

jQuery provides developers with many ways to add, append, insert, and update elements into the DOM that could not be demonstrated within a single recipe. Ensure that you are aware of the alternatives by reading the jQuery documentation.

See also

  • Inserting content into an element
  • Removing DOM elements
  • Re-using 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