jQuery 3 - Creating & Modifying The DOM |
Written by Ian Elliot | |||||||||||
Monday, 31 October 2016 | |||||||||||
Page 4 of 4
Building A Dynamic TableWe 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:
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:
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:
Now we have a row object we can create some data cells and append them:
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:
The complete function is:
To use it you would simply call it and append the result to whatever element you wanted to:
There are many ways of creating a table using jQuery and you can argue 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 addin and preferably a jQuery UI widget - which is something we will find out how to do in a later chapter.
More Information
Available as a Book:
buy from Amazon
Also Available:buy from Amazon
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.
Comments
or email your comment to: comments@i-programmer.info
|
|||||||||||
Last Updated ( Wednesday, 30 November 2016 ) |