Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to add elements html dynamically with JavaScript

This tutorial covers about how to add or remove rows in a table of a HTML dynamically using JavaScript code.

When working with dynamic data coming from the back end you must create the necessary DIV containers and HTML elements and append the new elements into the document body. In Fire Fox you can create a new element using the create Element method on the document object.

HTML documents can be easily accessed and manipulated using HTML DOM, which represents an HTML document as a tree-structure. When an HTML document is loaded in a browser window, it becomes a Document object. Now we can use the Document object to access to all HTML elements (as node objects) in a page, using any script such as JavaScript. Using Document object, we can add or remove element in the html as we do for xml.

Adding a new element to a document is very logical. The first step is to create the node (element) you wish to append, the next is to find where you wish to append it within the document, and the final step is to actually do the appending. A node is the representation of either a piece of text or a tag and its attributes in the DOM, and will be referred to often on this tutorial. The syntax for creating a node is very simple - you just call a method of the document object.

As a JavaScript developer, you may come to a point in your life where you’re just plain sick of going and writing HTML. Today, we’ll see how we can use JavaScript to create the elements in our HTML page so that we don’t have to do it “by hand”. Here’s what the initial HTML page should look like:

Listing1: A simple HTML setup

<!DOCTYPE html>
 <html xmlns="http://www.w3.org/1999/xhtml">
 <head>
     <title> Dynamic DOM Elements </title>
     <script type="text/javascript" src="main.js"></script>
 </head>
 <body>
     </body>
 </html> 

Web page content is usually generated and assembled on the server side and then sent to user browser. Server side content processing allows enforcing various rules such as validation, authorization, personalization, etc. It is, however, possible to add dynamics to the content on the client side by acquiring additional or modifying existing content and re-integrating results with the page without server round trip. Below we show how this can be achieved.

To implement dynamic content on a web page, the page should include a content container HTML element, which is usually a div element. For example:

Listing2: Reflects the div element

<div id="DynamicContent">
</div>

When this HTML element is rendered by the browser, this container element does not display anything - content is empty. This is usually initial state of the container element. If more than one similar container elements are placed on a web page, each should have a unique value of the id attribute.

To populate a container element with content derived from external sources (for example report output, HTML form content, list of links, etc.), there should be an event, which executes a java script code:

Listing3: Event executing the JavaScript code

Var oContent = document.getElementById(‘DynamicContent');
var cURL     = 'http://www.servername.com/path/servicename.aspx'
oContent.innerHTML = aaSubmitURI(cURI, "@GET", "");

In this example, the first line establishes object reference to the HTML container element which we created above, the second line provides URL of the web service which generates dynamic content to be placed into the container element, and finally the third line executes the web service, gets the content and updates the inner HTML of the container element to present the derived content.

Step 2: The JavaScript

JavaScript has some very helpful functions that we’ll be making heavy use of; .createElement() and.appendChild(). The first is pretty self-explanatory and helps us to create a new element by passing in a DOM element name. The second allows us to insert an element by calling on the parent element that will house the new child element.

We’ll start by first storing a newly created element in a variable. This will help us to call other functions on the element later to add styles and such. Let’s create a new div element and store it in a variable called newDiv:

Listing4: Creating a new div element and storing it in a variable.

var newDiv = document.createElement('div');

We can now refer to the newDiv element when we want to manipulate it.

The next step is to use the appendChild() method to place our newly created div into our HTML page. Since we’ve yet to add any elements to the page, we’ll need to call the body element and append our new div to it.

Here’s what it looks like in code:

Listing5: Appending the new div to the body of the page.

document.body.appendChild(newDiv);

Now, although at this point you cannot see the div, if you use your favourite DOM inspection tool to check out the page, you’ll see that we have, in fact, added a new div element to the page. JavaScript is even smart enough to add the closing tags and all!

If this isn’t enough awesomeness for you at once, just know that we can actually manipulate the CSS from here as well. JavaScript also includes a .style attribute that will allow us to change nearly any CSS property we’d like. Let’s go ahead and add some styling to our new div now:

Listing6: Adding some style to our div element

newDiv.style.width = "500px";
newDiv.style.height = "500px";
newDiv.style.background = "#77a4d4";
newDiv.style.borderStyle = "solid";
newDiv.style.borderWidth = "1px";

As you can see, we’ve given our div some definition now, and you should be able to view the finished product in the browser in all of its glory.

Conclusion

The power of what we seen today is that we are creating and styling elements “on the fly”. We used the term loosely because we’re not actually doing anything dynamic here. However, there’s nothing stopping you from doing any of this within an event handler such as onClick or onMouseOver which would make creating the elements completely dynamic.



Software Developer from India. I hold Master in Computer Applications Degree and is well versed with programming languages such as Java, .Net, C and C++ and possess good working knowledge on Mobile Platforms as well.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login