Discussing the nuts and bolts of software development

Friday, April 04, 2008

 

Creating Dynamic HTML Content

For the uninitiated, the whole concept of generating new HTML through JavaScript can be pretty intimidating, but it certainly remains a powerful and easy way to alter a web page on the fly, especially since all the popular browsers support it nowadays.

The HTML DOM

The Document Object Model is an API which allows you to access and modify the contents of an HTML document through a client-side script such as JavaScript. The current content of the page, as stored in the browser, is represented by a tree of nodes. Any element found within the page (such as a paragraph block

) will correspond to an object (like HTMLParagraphElement), and in turn anything contained within that element (even plain text) will be accessible as childs of that node.

There have been DOMs ever since web browsers started supporting Javascript, but the one used here (and the standard nowadays) is the W3C DOM that is supported (albeit not quite perfectly) by IE 5+ and Mozilla.

One very important thing to understand right off the bat is that the DOM is an interface model. The objects you'll be invoking in your scripts are ways to access the document data, but they're not actual containers. This means you're not going to create them like you create Java objects, and that you'll be able to work with any kind of node on a general level without having to use the specific object for it.

Creating new HTML objects on the fly

The simplest way to generate content is to invoke the createElement() method of your document object.


var myNewParagraph = document.createElement("p");


Simple as that! A new node of type paragraph is created out of thin air, just as if you had entered "<p></p>" in your document source. But where will this new element end up? You'll have to specify that by "inserting" it into your document. For instance:


// Appends the paragraph at the end of the form
document.myForm.appendChild(myNewParagraph);

// Appends it to the beginning of the form
document.myForm.insertBefore(myNewParagraph, document.myForm.firstChild);

// Replaces another element altogether
document.myForm.replaceChild(myNewParagraph, document.getElementById("MyPlaceholder"));


As you can see, there are several ways to get to the proper insertion point. The methods supported by a parent node are appendChild(), removeChild(), replaceChild() and insertBefore(). Any given node also has the following properties to help you traverse the data tree: firstChild, lastChild, nextSibling, previousSibling and parentNode. What more can you ask for?

Altering properties

Adding new elements is all well and good, but what about setting attributes? The easiest way to do so would be with the following "generic" call:


newCell.setAttribute("width", "25px");
newCell.setAttribute("align", "right");
newCell.setAttribute("myAttribute", "myValue");


The setAttribute() method works pretty much as if the text "myAttribute=myValue" had been written inside the element's tag. I say "pretty much" because I've experienced problems with it when I tried formatting everything that way. Style classes, notably, never worked quite right. Because of this, I'd suggest doing all your attribute settings through object properties, like so:


newInput.type = "text";
newInput.style.width = "100%";
newInput.className = "myClass";
newInput.name = "MyUserBox::" + myIndexValue;
newInput.id = newInput.name;
newInput.value = "[Please enter a value]";


Any standard HTML attribute should have a corresponding object property, although the names don't always match - you might need to do a bit of research to find the right property.

Taking shortcuts

By now you're probably annoyed at the idea that you'll have to write several lines of code for each and every HTML element you need to create. Well, you're not the only one. Several shortcuts are supported by the standard browsers. For instance, the following should work just fine:


var myNewParagraph = document.createElement('<p style="text-align: right;">I don\'t see <b>WHY%lt;/b> I should set everything manually' +
'if this approach actually <a href="http://www.macadamian.com/">works</a>!</p>');


Of course, the following approach requires the browser to do some parsing, and is therefore much slower than the official one. But then again, on a modern machine, you're not likely to notice it.

Another gift from Heaven is the "innerHTML" property, which allows you to not only see the HTML representation of what an element contains, but also to edit it on the fly, having it parsed in a similar manner:


var myNewParagraph = document.createElement("p");
myNewParagraph.style.textAlign = "right";
myNewParagraph.innerHTML = 'This can be even <b>COOLER</b> because you don\'t have to create a new object. You could just ' +
'change the property of an old one and it should still <a href="http://www.macadamian.com/">work</a>!';


There is also an outerHTML property which shows the whole tag corresponding to its element, not just what's contained in it. You can even set its content, just like innerHTML, but I wouldn't touch that with a 10-foot mouse.

Tables

Tables elements (TABLE, TR, TH, TD) are trickier than most elements. For one thing, their inner/outerHTML properties are read-only. They should also be added and removed with a different (but overall nicer) syntax:


var myNewRow = myTable.insertRow(); // Add a row at the bottom of the table
var myNewCell = myNewRow.insertCell(); // Add a cell at the end of the row
var myNewFooterRow = myTable.tFoot.insertRow(2); // Add a row before the 3rd one, within the footer
myTable.tBodies[0].rows[0].deleteRow(0); // Delete the 1st cell of the 1st row of the 1st block


insertRow() and insertCell() can take an index stating where the new element goes, or it will simply add it "at the end". Note that you can work with rows at both the table and section levels (deleting the Nth row of the table vs deleting the Nth row of the header), so be careful and know the different between the rowIndex and sectionRowIndex properties.

Final notes and warnings

When dynamically altering your page, be prepared to do a lot of trial and error, and don't forget to test your code on every platform you intend to support.

Finally, if something doesn't work, try a different syntax and/or approach. There's more than one JavaScript way to skin an HTML cat...

Labels: , ,


Comments:
Great.. Tutorial is just awesome..It is really helpful for a newbie like me...

JavaScript Online Training JavaScript Online Training JQuery Online Training JQuery Online Training
JavaScript Course | HTML5 Online Training
 
I am sure that here you will learn more about dissertation defense. I had such experience recently
 

This was an outstanding piece of content. I really liked it. I'll be back to see more. Thanks!

Also visit my webpage - 부산오피
(jk)


 
Genuine leather jackets are made from real animal hides, such as cowhide, lambskin, sheepskin, or goatskin. Each type of leather has its own unique characteristics, such as thickness, texture, and suppleness.
 
What an awesome way to explain this-now I know everything!
 
No complaints on this end, simply a good piece you made
 
It's really great that people are sharing this information. more plss
 
I very much like and agree with your point of view. Thank you
 
Very informative blog! I am glad that I came across your article. Discover the ultimate learning experience with Ziyyara Edutech, the world's largest online education platform offering comprehensive and personalized home tuition classes for Class 12 students.
Book A Free Demo Today visit Private tuition classes for class 12
 
Normal woven hessian and material impart comfort in indoor nurseries and supplement existing vase adornments. 8 inch pot
 
As a student who recently sought assistance from British Coursework Help, I can confidently say that their services exceeded my expectations. From the initial inquiry to the completion of my assignment, the team displayed professionalism, expertise, and unwavering dedication. Their meticulous attention to detail ensured that my coursework was not only delivered on time but also met the highest academic standards. Moreover, their willingness to accommodate my specific requirements and provide personalized support truly set them apart. I highly recommend british coursework help to any student in need of reliable and exceptional academic assistance.
 
Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?