Just jQuery The Core UI - Creating Objects
Written by Ian Elliot   
Thursday, 29 December 2022
Article Index
Just jQuery The Core UI - Creating Objects
Inserting New Elements
Moving and Cloning
More Wrapping
Inserting
A Dynamic Table

Building a Dynamic Table

We could continue with the theory of DOM creation and manipulation for a lot longer, but it is time for a simple example.

Suppose you want to generate a table dynamically. Then what you need to do is build a sub-tree with the required rows and data cells. The best way to do this is to create a function so that you can stamp out as many tables as you require:

function table(n, m) {

In this example the table will have n rows and m columns but you can add additional parameters, or better an options object to set other details of the table.

The first thing to do is to create one object of each type that we are going to use to build the table – one table, one table body, one table row and one table data cell:

var table = $("<table>"); 
var tbody = $("<tbody>"); 
var row = $("<tr>"); 
var cell = $("<td>");

The idea is that once we have one of each type of object we can build the table using append.

First we need to create n rows and the simplest way to do this is to use a for loop and the clone method to create a new row object.

You might say why not just create a new row object, but the idea is that if the row object has already been customized in some way it is simpler to stamp out copies than to create new objects from scratch:

for (var i = 0; i < n; i++) { 
 var tempRow = row.clone();

Now we have a row object we can create some data cells and append them:

for (var j = 0; j < m; j++) { 
  tempRow.append(cell.clone().html(i+","+j)); 
}

Again the clone method is used so as to replicate any custom settings on the basic cell object. Notice that to give the table something to display we use the html method to add some content – the row and column number.

Once the row has been built we can append it to the table body and let the row for loop continue.

Finally we append the table body to the table object and return it as the result:

tbody.append(tempRow); 
} 
table.append(tbody); 
return table; 
}

The complete function is:

function table(n, m) { 
 var table = $("<table>"); 
 var tbody = $("<tbody>"); 
 var row = $("<tr>"); 
 var cell = $("<td>"); 
 for (var i = 0; i < n; i++) { 
  var tempRow = row.clone(); 
  for (var j = 0; j < m; j++) {
   tempRow.append(cell.clone().html(i+","+j));
  } 
  tbody.append(tempRow); 
 } 
 table.append(tbody);   return table;  }

To use it you would simply call it and append the result to whatever element you wanted to:

$("body").append(table(3, 2));

There are many ways of creating a table using jQuery and you can argue about issues of efficiency verses elegance. If efficiency isn't a big issue, and with browsers and JavaScript engines getting faster it often isn't, then this sort of construction is easier to understand and more logically structured than yards of HTML.

Of course, if you really want to create an "enterprise" quality custom control, you probably should create, at the very least, a jQuery plugin and preferably a jQuery UI widget, which is something we will find out how to do in Chapters 14 and 15.

Summary

  • If you make the call $(string) then, if the string parses to valid HTML, the elements it contains are created as a DOM sub-tree. If the string isn't valid HTML, then jQuery attempts to interpret it as a selector and to return the corresponding elements as an array in a jQuery object.

  • If you pass a complex HTML string then it creates a single object for each element at the top level with other objects nested within it as the markup dictates. 

  • There are three distinct ways of inserting new objects into the DOM:

1. Insert as child

  • The append method element1.append(element2); appends element2 as the last child of element1 and returns element1.

  • The appendTo method element1.appendTo(element2); appends element1 as the last child of element2 and returns element1.

  • The prepend method element1.prepend(element2); appends element2 as the first child of element1 and returns element1.

  • The prependTo method element1.prependTo (element2); appends element1 as the first child of element2 and returns element1.

  • When you append to an array of objects a copy of the object being appended is automatically created.

  • When you append an object more than once a copy isn't created and the original object is just relocated i.e. moved.

  • If you want to append multiple copies of an object use the clone method to make a copy.

2. Insert as parent

  • wrap(element) will take each element in the results list, place it inside the specified element as a child and then replace the element in the DOM.

  • wrapAll doesn't wrap each result with its own clone of the specified element. Instead it wraps all of the results by a single element.

  • wrapInner works like wrap but now it wraps the content of each element in the results.

  • unwrap() will remove the parents of each element in the results.

3. Insert as sibling

  • The before method inserts the new elements before each of the elements in the results array and the after method inserts them after. 

  • insertBefore and insertAfter insert the new element before or after the target respectively.

  • There are two methods that replace existing elements: .replaceWith(newElement); replaces every element in the results array by the newElement

    .replaceAll(target); replaces all of the target elements with the results.

  • The empty function removes all of the children from each element in the results list.

  • The remove function completely removes all of the elements in the result that match the specified target.

 

 Available as a Book:

smallcoverjQuery

buy from Amazon

  1. Understanding jQuery
  2. Basic jQuery CSS Selectors
       Extract: The DOM
  3. More Selectors
       Extract: Basic Selectors
  4. The JQuery Object
  5. Filters 
  6. DOM Traversal Filters 
  7. Modifying DOM Objects
       Extract: Modifying The DOM 
  8. Creating Objects & Modifying The DOM Hierarchy
  9. Working With Data
       Extract: Data ***NEW!!!
  10. Forms 
  11. Function Queues
  12. Animation 
  13. jQuery UI
  14. jQuery UI Custom Control
  15. Easy Plugins 
  16. Testing With QUnit
  17. Epilog A Bonus Function

Also Available:

jquery2cover

buy from Amazon

 

Banner
 

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

 

espbook

 

Comments




or email your comment to: comments@i-programmer.info

<ASIN:1871962501>

<ASIN:1871962528>

<ASIN:1871962560>



Last Updated ( Thursday, 29 December 2022 )