with Imagination: by Dustin Diaz

./with Imagination

A JavaScript, CSS, XHTML web log focusing on usability and accessibility by Dustin Diaz

Add and Remove HTML elements dynamically with Javascript

Monday, February 28th, 2005

UPDATE: There is a newer “up-to-date” version of this entry posted on January 02, 2008. View Add and Remove Elements with JavaScript (reprise).

I’m going to tell you straight up front. I hate Javascript. I hate it because it owns me. Today, it owned me. But within a few hours, I reversed the curse (In my past life I was a song writer).

In the following article, I’m going to show you how you can dynamically create HTML elements with content wrapped within them according to the DOM2 specification. Why would this be useful? Just take one look at the add/remove HTML element demo.

Those who have a GMail account probably recognize its similarity to the attachment feature when composing new email. Since Gmail’s javascript seems to be hidden… or scrambled… or… whatever they did to it, I was left in the dark trying to figure this one out on my own.

Read on to see some explanation of this garbagio that had me tearing my hair out. Lastly, just as a heads up, it may be better than you read the rest of this article using the Undesigned style sheet so that you may have better readability of the code.(Only available on old site design)

First of all, the (x)html is real simple.

xHTML Snippet

<input type="hidden" value="0" id="theValue" />
<p><a href="javascript:;" onclick="addElement();">Add Some Elements</a></p>
<div id="myDiv"> </div>

The hidden input element simply gives you a chance to dynamically call a number you could start with. This, for instance could be set with PHP or ASP. The onclick event handler is used to call the function. Lastly, the div element is set and ready to receive some children appended unto itself (gosh that sounds wierd).

Mkay, so far so easy. Now the JS functions.

addElement JavaScript Function

function addElement() {
  var ni = document.getElementById('myDiv');
  var numi = document.getElementById('theValue');
  var num = (document.getElementById('theValue').value -1)+ 2;
  numi.value = num;
  var newdiv = document.createElement('div');
  var divIdName = 'my'+num+'Div';
  newdiv.setAttribute('id',divIdName);
  newdiv.innerHTML = 'Element Number '+num+' has been added! <a href=\'#\' onclick=\'removeElement('+divIdName+')\'>Remove the div "'+divIdName+'"</a>';
  ni.appendChild(newdiv);
}

removeElement JavaScript Function

function removeElement(divNum) {
  var d = document.getElementById('myDiv');
  var olddiv = document.getElementById(divNum);
  d.removeChild(olddiv);
}

The addElement function sets a variable by grabbing the element of which we will append a child node to. So in this case, we use the classic getElementById method to track it down. We of course supply the empty ‘myDiv’.

The next three lines basically grab the value of the hidden input element and give your function a starting number to begin with. Then each time the function is called, your value is incremented. This is important for when you need to remove elements, since you’ll need unique id’s.

You’ll notice next the createElement is used to… well… make a new div element. But wait, it needs an id. Thus, we use the setAttribute method to append an id and a value to it. At this point, we have the uniquely named divIdName and we will plug that into the equation for our newdiv object.

Now you’re ready for some content garbagio to put inside your dynamic div element using the innerHTML property. And this is when it gets fun. Within your HTML supplied in the innerHTML of the dynamically created div element, you need to provide a link to remove itself. Afterall, that’s the point of this whole thing, right? It wouldn’t be flexible if all we could do is only add and not remove.

So, a link is put inside with an event handler that calls the function removeElement. Great. Simple enough. Let’s move onto that function.

Okay, now that is easy. First off, it grabs the same parent div element by using getElementById and stores it in a variable. We then get the element to which we passed in as an argument to the function (which was created from the addEvent function), and we store that in another variable. Then voila! We remove like so:


d.removeChild(olddiv);

Play with it, study it, tell your Uncle about it. This may not seem like a big deal, but it has potential to do some really cool stuff.

283 Responses to “Add and Remove HTML elements dynamically with Javascript”

  1. Justin Perkins

    Ahh, DOM. I love it so much. Glad you’re finding that Javascript is not all evil.

    Adding a DIV is not really an event though, watch what you call your functions as they should make sense to other people not familiar with your code.

  2. Justin Perkins

    Maybe I should qualify that a little bit…

    An event is something like a hover, click, keypress, load, etc. An “event handler” is activated when the event occurs.

    This would be a typical “addEvent” function in Javascript:

    function addEvent(obj,evType,fn,useCapture){
    var ret=false;
    if(obj!=null){
    if(obj.addEventListener){
    obj.addEventListener(evType,fn,useCapture);
    ret=true;
    }
    else if(obj.attachEvent){
    obj.attachEvent(”on”+evType,fn);ret=true;
    }
    }
    return ret;
    }

  3. Dustin

    just to be clear on what I was doing Justin, I was pulling this from a “Track & Field” add Event module. Event in this case stands for the Athletes Event such as high jump, pole vault or the mile.

    I know exactly what the differences are ;)

  4. Chris

    Good article. Just what I was looking for!

  5. Dave Greiner

    Awesome tips, thanks so much Dustin. This will come in super handy for an upcoming app I’m working on.

  6. Samuel

    Excelente Sr. Diaz. Muchas gracias.

  7. Chris Peters

    Consider your code raped and pasted. Thank you for helping out with this great article. :)

  8. Dustin Diaz

    I’m glad you’re making sweet love to it.

  9. Loic Deniel

    Thanks again for this Dustin, this is really cool

  10. Dustin Diaz

    Just a heads up. I took some of Justin’s advice and renamed the original functions to addElement and removeElement just so that one doesn’t get confused with Scott Andrew’s famous addEvent function.

  11. Chris Peters

    Not only will I be making sweet love to it. But all of the workers for Franklin County, Ohio, will be making sweet love to it on their Intranet.

  12. cro

    this is just what i was looking for… but i became greedy. any chance to build up an entire page this way? say, write a .js to spawn the whole thing or something like that? seems to work on anything inside a page, but i can’t figure out how to start one from scratch.
    thanks anyway

  13. Dustin Diaz

    The Demo shows how to create sample content. And although it’s not W3C DOM methods (since it uses innerHTML) it’s pretty widely supported and there are plenty of folks requesting that it becomes a standards. I mean really, it’s so easy to use.

    So for your purpose, I suppose, you could try just setting up separate blocks of code you want to insert as html, and call them out upon clicking on different options etc.

    So yea, in short: You can create an entire page from scratch given the right tools. That is the pretty much the entire idea of a WYSIWYG Editor.

  14. Elio Todaro

    I don’t have a reply but a question.

    I need to remove an html input control which was not created dinamically.

    I tried removeChild but it didn’t work.
    Any suggestion will be appreciated.

  15. Dustin Diaz

    Elio,
    A typical way to delete an element since there is no removeElement DOM method, you need to grab a reference of the element, find it’s parent, then remove the element reference.

    eg.
    var el = document.getElementById('abc');
    el.parentNode.removeChild(el);

  16. Elio Todaro

    Thanks for your help Dustin,
    now everything works.

  17. Sreeni.A

    Hi freinds ,
    In a html page I am creating a row with three form elements ( 2 text boxes and one select box) dynamically just by pressing a button. But now how can I code it to remove the row which is created lately?

    Can anybody help me please?

    Sreeni.A

  18. Dustin Diaz

    remember to target your elements with an object finder like getElementById or getElementsByTagName. If you have <input id=”test” type=”text” /> and you want to remove it… you simply invoke a function that does the following:

    function rem() {
    var t = document.getElementById(’test’);
    t.parentNode.removeChild(t);
    }

    You can invoke the function with any event you like. The most simple and obvious is a click event. For instance, have a link fire off a function like the one I just wrote.

    Hope that helps.

  19. Amol M Vaidya

    Thats a really cool article, simple and sweet. A thousand thanks for that

  20. John

    How would you do this for a form? For example, I want to give a user the option to upload multiple files. Do I add the newly created elements to the form?

  21. Dustin Diaz

    John,
    Funny you mention that. This post was originally inspired from that problem. My idea was to create something similar to the gmail uploader to attach files.

    Easy enough, name your input elements with an array like <input type=”file” name=”files[]” /> and you can catch them in php by counting the array length. Thus, when you’re creating new element, just do it as so:

    function makeInput() {
    var input = document.createElement(’input’);
    input.type = ‘file’;
    input.name = ‘files[]’;
    }

    Make sense?

  22. John

    Thanks, makes sense, but don’t you lose the ‘removeElement’ functionality?

  23. Christina

    This is lovely. I’m climbing up the steep side of the DOM learning curve; and it’s a huge help to find explanations and examples.

    Would anyone else around here feel like showing any working examples of this, so we can join all the workers in Franklin County, Ohio?

  24. John

    I figured out how to attach it to my form and everything works just like I want it. Thanks , this will work well in the application I’m building. :)

  25. Slim Shady

    > Dustin said:
    > just to be clear on what I was doing
    > Justin, I was pulling this from a
    > “Track & Field” add Event module. Event
    > in this case stands for the Athletes Event
    > such as high jump, pole vault or the mile.

    > I know exactly what the differences are

    very helpful article

    (even if dustin’s a little sensitive about his coding skills ;) )

  26. Hannes Baldursson

    Regarding upload forms, I have a much cleaner method. Stickmans blog

    Pretty neat idea. I do it diffrently, and it’s currently not working :-p

    You can see my version, and problem on free2code.com forums

  27. Tom

    Hi, very nice example.
    I tried it online and it was ok, but when I copy
    the source code, and try it on my machine it doesn’t work. It was not possible to remove the items.
    Is it possible that in the code , I have to write a pagename instead the javascript?
    And which page?

  28. Tom

    Sorry, to my question forward. We code I mean is:

  29. GeniX

    Great example, i’m gonna steal it, thx!

  30. Chris

    Just wanted to say thanks for a great howto! This was exactly what I was looking for. I’m no javascript expert, but I was able to modify the code to work nicely with some form fields.

  31. ShorTTy

    I have been scouring the ‘net and Googling for aaages for a decent AJAX tutorial that does exactly this… I HAVE FOUND THE HOLY GRAIL. =)

    Thank you so much, my life is now complete. Off I go, getting my head around this new technology.

    This is the best site ever.

  32. Dustin Diaz

    ShorTTy,
    Your life will soon begin. I’m glad I could tell about just a few of the basics since -in fact- these are the details most sites leave out. I hate that, don’t you?

  33. mynameis

    This was helpful to me ..but not fully….
    I’m adding a set of elements(which contains 2 text areas and radio button.) the radio button when clicked will open up text box.
    Now I am able to get these new appended sets. But the appended sets show js error when I click the radio button and doesn’t show the text box.
    Pls reply asap

  34. Dave L

    Nicely done! I had nearly given up searching when I found your tutorial. I adapted your technique to work with file type input boxes too.

    Sincerely,

    David Levin

  35. Yong Chen

    Dear Dustin,

    I am working on a project which needs a functionality of selecting multiple file at a time on the client side for uploading several files to the server.

    I found the following code snippet somewhere, but i encountered the error “mFile.children.valueis null ” when using it. Could you please help me.

    function mCreateFile(obj){
    var eF
    var mName
    mFileName.innerHTML=”"
    if (obj.id==”File”) {
    for (i=0;i”+mName[mName.length-1]+”"
    }
    }
    mstatus.innerHTML=”总共有 “+(mFile.children.length-1)+” 个文件等待上 ”
    }

    if (obj.id==”File_New”) {
    eF=document.createElement(”)
    mFile.appendChild(eF)
    obj.id=”File”
    }
    }

    table{
    FILTER: progid:DXImageTransform.Microsoft.Shadow(direction=135,color=#999999,strength=3);
    }
    input{
    border:1px soild #000000;
    font-family:Verdana,Arial,宋体;
    font-size:12px;
    padding:2px;
    }
    #mTD{
    LINE-HEIGHT: 24px;
    }
    #mFile{
    width:203px;
    float:left;
    |
    #mFileName{
    float:right;
    width:182px;
    }
    #NameDetail{
    overflow:hidden;
    width:176px;
    color:#000000;
    font-family:Verdana,Arial,宋体;
    font-size:12px;
    cursor:default;
    height:22px;
    }
    #mstatus{
    font-size:12px;
    color:#ff0000;
    }

    添 附件

    总共有 0 个文件等待上

  36. ScorpRash

    Dear Dustin,

    In my project I am having a html button control generated dynamically through .NET c# language. I have added attributes and associated javascript function to that control. Till that its fine.
    Now my requirement is based on some input from user I need to dynamically APPEND or REMOVE the javascript event hanlder to that control.
    Say, If for button “onClick” i have “func1();” and “func2();” associated, I may need to remove “func1();
    dynamically and add “func3();” to the same “onclick” event. I wish to accomplish this using javascript. Is it possible? If so, can you please advice.
    Note: The control and its id are also known only at runtime (i.e., When we go for Page view source).

  37. Priya

    Here’s an offshoot - I need to add a form element dynamically to my HTML - would I use a concept similar to above? Great article by the way!

  38. Sanket

    Hi there,

    This article is really GREAT !! I was searching for this, since last year. And after about an year, Ultimately I got it. My thanks to the creator of Script

    Sanket

  39. shipra

    Hi,
    Nice article.It has solved one of my problem,Thanks .
    There is another problem iam facing.Like in Gmail, how do upload the file?
    Where and how to call the auto save for attach file?

    If you could help please do reply.
    Thanks a lot

  40. Peter

    Hey Dustin, thanks for the code snippets, looking to incorporate them into a coming project but I’m having trouble and thought you might be able to help. I need to dynamically create not 1, but 12 inputs, and 1 text area. So, they press a button, 12 text fields and 1 area. Press it again? 12 more inputs and 1 area, etc. Ive tweaked your code to be able to dynamically generate all the fields I need, complete with names, values and type definitions…however…its..ugly. I need to format it, wrap it inside (hate to say this cause im a css standards guy…) a table and thats where everything breaks. Append merely chucks it at the bottom of the DIV, I need to be able to control where it goes, and to format it by appending it right inside a specific TD. Is this possible? I tried innerHTML but that defeats the purpose of the DOM2 compliant code, and didnt necessarily work either. Not even sure you’ll get this, but thanks nonetheless for some great code. Cheers-

  41. Dustin Diaz

    Hey Peter. The innerHTML dillemma is one that I refuse to tackle right now. It’s fully supported even on ie5.x browsers so I’ve yet to find a good reason not to use it. Sure it’s not in the standard DOM2 specs, but it’s even getting more highly adopted as it is now effective in Firefox 1.5 for XML which only shows that it’s more likely to get adopted sooner or later by the W3C.

    Another thing you can do is put a generic ‘div’ element in the spot you wish to put your dynamicly created content, then use appendChild or innerHTML in that spot.

    Also, make sure your html string is all on one line in JavaScript. That will break your code.

  42. Alexandru

    Hy! I tried to get files from a php script and it wasn’t the name of the file ! it was the name of the temp file! $file[0] will return the temp file copied to server temp folder!

  43. Jeff

    Hi,
    I’ve been reading your site for some time. First, thanks for all the work and help!!! I’m just getting into javascript and DOM so I hope you can bear with me. I have succesfully used the script for my own purposes but now I am trying to add a set dynamic radio buttons that when clicked show or hide a corresponding div with additional form info. There are three divs and three radio buttons, I’ve tried using several different methods I was able to find but the usual error I get is that the function is not defined. I’ve tried everything I can to get it ot work without success. Is there something obvious I’m missing here? I’m dying to figure this out now for peace of mind more than anything else? I greatly appreciate your insite.

  44. Ajay

    hi,i have two buttons called accept and reject

    and inside the body of my html,i have one div tag as follows

    Response ;

    when the user clicks on accept i want to replace

    Response ;

    as

    Response ; accept

    if the user clicks reject i need to make this as

    Response ; reject

    any luck

  45. mdani

    Halo Dustin
    i have checked the following script but i had error on remove function
    and set for the better one:
    this is from your site

    function removeElement(divNum) {
    var d = document.getElementById(’myDiv’);
    var olddiv = document.getElementById(divNum);
    d.removeChild(olddiv);
    }

    this is from me:

    function removeElement(divNum) {
    var d = document.getElementById(’myDiv’);
    d.removeChild(divNum);
    }

    tested on IE6 and FireFox 1.0.7

    CMIIW :)

  46. Dennis

    Great Code. I am having a problem that I cannot figure out. I am using ASP.NET 2.0. I want to make a Usercontrol that uses this code, but when I post the data using the ASP.NET button the added controls are not seen and I cannot figure out how to access them. After the postback and the page is rerended to my browsder all the added controls are gone.

    Any ideas on what I am doing wrong and how to work arround this issue?

    All code below:

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    For Each oControl As Control In Controls

    Stop

    Next
    End Sub

    var email_count=0;

    function remove_email(emailid) {
    var d = document.getElementById(’emailtable’);
    var olddiv = document.getElementById(’e’ + emailid);
    d.removeChild(olddiv);
    }

    function add_email() {
    email_count++;
    var html=’Type’
    html+=’HomeBusiness’
    html+=’Required’
    html+=’Address’
    html+=’Required’
    html+=”;

    document.getElementById(”emailtable”).innerHTML += html;
    }

    Test Page

  47. Dennis

    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    For Each oControl As Control In Controls

    Stop

    Next
    End Sub

    var email_count=0;

    function remove_email(emailid) {
    var d = document.getElementById('emailtable');
    var olddiv = document.getElementById('e' + emailid);
    d.removeChild(olddiv);
    }

    function add_email() {
    email_count++;
    var html='Type'
    html+='HomeBusiness'
    html+='Required'
    html+='Address'
    html+='Required'
    html+='';

    document.getElementById("emailtable").innerHTML += html;
    }

    function div_delete() {
    //document.getElementById("div1").innerHTML.delete;// = "";
    }

    Untitled Page

  48. Sraan

    Hi,

    i was searching for adding an event to a dynamically created element and got to your website.

    Is there any way to add a event dynamically(ex:onClick=”openWin(xxxxx,xxx);”) to the dynamically created element?

    I am trying to get it work and no luck so far.

    thanks
    Sravan

  49. Sraan

    Hi,

    finally i got it to work. But for some reason it just works in Netscape. It won’t fire onclick event in IE when i click the “Add” button for created row. Any ideas??

    Here is the code..

    function addRow()
    {
    //get the table body for which to add a row
    var tbody = document.getElementById(’table1′).getElementsByTagName (”tbody”)[0];
    var lastRow = tbody.rows.length;
    var iteration = lastRow + 1;//get the last row of the table and one for new row
    //var tbody = document.getElementById(”table1″).getElementsByTagName(”tbody”)[1]; //get the tbody element
    var row = document.createElement(”TR”);
    var cell9 = document.createElement(”TD”);

    cell9.style.textAlign = ‘center’;
    cell9.className = “tbltan”;
    var inp9 = document.createElement(”INPUT”);
    inp9.setAttribute(”type”,”button”);
    inp9.setAttribute(”name”,”bal_by_source” + iteration);
    inp9.setAttribute(”value”,”Add”);
    inp9.setAttribute(”size”,”10″);
    inp9.setAttribute(’onClick’,”openWind(’xxx.cfm’,” + iteration + “);”);
    cell9.appendChild(inp9);

    row.appendChild(cell9);
    tbody.appendChild(row);
    }

  50. Sean Hudson

    Dustin,

    First off, thanks for the article. I *think* I am starting to get the basics down, and articles like this really help. I learn well by example.

    However, I do have one problem. I cannot get the removeElement to work properly. I copied the example directly from your page, but it no workie.

    Thanks,
    Sean

  51. Cid

    It’s a great code but how can I customize the div?

    I’d like to position it and put it above the other HTML content.How can that be achieved?

    Thanks

  52. Scott Martin

    Just though I would say great example and with only a little tweaking got it to add new ’s and remove them then let me add the same line agian.
    Image map selection for selecting different areas and adding them to their list, then removing them, then adding them agian, etc..
    Thanks agian.

  53. Guest

    Thumbs up!

    I modified the script to show INPUT field instead of plain text after clicking “add”…
    newdiv.innerHTML = "";
    …but in Firefox (v1.5), after sending the entire FORM with these generated INPUT fields, none of them are passed nor recognized by REQUEST.FORM.
    In IE works fine. Help appreciated.

    Thanks!

  54. Clint

    Yea, I’m having the same thing happen to me. PHP just does not seem to “see” the form elements that I add via my addElement function… Anyone?

  55. Chandra

    Dustin
    Two pleasures in one - what a sweet copncept. I think I’m re-growing all the hair I lost trying to git-r-done with dynamic HTML and CSS.
    Cool abd concise.

  56. Adm.Wiggin

    Dustin: Thank you. Wonderful article. Used this stuff for some of the admin end of the Timpanogos Tribune. Beautiful.

  57. BBlackmoor

    This is a great tip. You saved me a lot of time figuring this out. Thanks.

  58. New2Arrays

    Great stuff! Very helpful. Can you show me how you write this using an Array so that I could do things like add up the Array values? My goal is to be able to take the dynamically created values and total some of them. Thank you.

  59. Pete

    Clint, this is from the Gecko DOM reference. I think it explains your dilemma.

    Note that when you append to the innerHTML of a document, you have essentially created a new document. The session history for the browser is incremented, and when you go Back, the document is there in its original, unappended state.

    I am in the initial stages of reseraching this– maybe if you don’t use innerHTML it would work.

  60. Dave Irvine

    Hi,

    i was searching for adding an event to a dynamically created element and got to your website.

    Is there any way to add a event dynamically(ex:onClick=”openWin(xxxxx,xxx);”) to the dynamically created element?

    I am trying to get it work and no luck so far.

    thanks Sravan

    Sraven, I’m having exactly the same problem. It works fine in netscape, firefox, but IE refuses to pick up on the fact i’ve clicked on an element I’ve just added that has a new onclick event… I’m doing something with dynamic ratings for articles, code as follows:

    objectToAppend = document.createElement("img");
    objectToAppend.setAttribute("src","images/starfilled.gif");
    objectToAppend.setAttribute("onclick","javascript:rate(" + starnum + "," + articleid + ");");
    objectToAppend.setAttribute("id","article" + articleid + "ratingstar" + starnum);
    d.appendChild(objectToAppend);

    Any ideas from anyone on how to get this working in IE?

  61. Dave Irvine

    Ok, so I answered my own question. The answer was in fact, in the example provided on this page… innerHTML!

    objectToAppend = document.createElement("div");
    objectToAppend.setAttribute("id","article" + articleid + "ratingstar" + starnum);
    objectToAppend.setAttribute("class","rateimg");
    objectToAppend.innerHTML = "&lt img src=\"images/starfilled.gif\" class=\"rateimg\" onclick=\"javascript:rate("+starnum+","+articleid+")\">";
    d.appendChild(objectToAppend);

  62. Crammit

    Hey ppl, have any of yous had any problems with either removeNode() and removeChild() in regards to crashing IE… for me when ever any of these functions are called IE quits unexpectedly with an error in mshtml.dll… Ive tried this on different computers however all seem to have the same problem… I found a MS hotfix for this however diddnt fix the problem :/ If anyone knows how to get around this Please Advise, Thanks.

  63. Qamar

    Hi
    I need to implement css class to the input element button i created using Inner HTML.
    Any help will be appreciated
    thx
    Qamar

  64. Dave

    Hey Dustin great example, works nice and easily implemented to a drag and droppable div to create dynamic workflow,

    thanks for the ideas

  65. John The Backpatter

    *pat*pat*pat*pat*pat*pat*pat*pat*pat*pat*

    Exactly what i was looking for , THOUGH…
    I’m actually taking a select from one iframe and recreating it in sister-frame, with minor alterations, this will do. THANKS!

    *pat*pat*pat*pat*pat*pat*pat*pat*pat*pat*

  66. Jesse

    Really cool example, but a quick question:
    Instead of adding a new div element, is there any way to simple populate an existing one? Basically, what I’m trying to do is generate an empty table, then go back and populate it dynamically from a database (sounds crazy, but trust me, there’s a reason for it). Any ideas?
    thanks!

  67. Jesse

    never mind, I figured it out. I was just blind, and didn’t see it, very simple example:

    testing set image value

    function addtext(){ document.getElementById(’testArea’).innerHTML = “Blah!”; }

  68. Guest

    Sraan,

    I have not tested this solution with your code, but a similar problem I had with IE and trying to use an attachEvent() call was solved by using “onclick” instead of “onClick.” Apparently IE is case-sensitive.

  69. SHISHIR RAJ ADHIKARI

    Good one.Thanks for it.I was looking for it very badly.

  70. suchitra

    Hi,

    After adding element dynamically some rows, then how can i edit those rows.

    It’s cool code..

    suchitra

  71. Laurence

    Hi, is there any way to dynamically create a media player with the source depending on the result of a query string passed to it from the previous page with the coded link? I am able to pass the query between pages ok, but haven’t figured out how to pass the result to the source attribute of an embedded media player.

    Any help is appreciated. Cheers.

  72. dane

    Hey love your tut :) Thank God for people like you..

    Ive noticed a bit of typo in newdiv.innerHTML .. you might want to check it..

  73. Tom

    If you want a good place to go for AJAX examples and tutorials, try http://ajaxpatterns.org.

  74. Tony

    ShorTTy mentioned that he had been “Googling for aaages for a decent AJAX tutorial that does exactly this”, I feel obligated to point out that this is NOT AJAX. There is nothing AJAX about this functionality. Ajax is Asynchronous JavaScript And XML, by the very basic nature it’s suppose to interact to a server; this example here does no such thing. It merely changes client side and has no interaction with a server.

    http://en.wikipedia.org/wiki/AJAX

  75. Dave

    PLEASE HELP!! I can not implment the code to work.

    “+”"+”"+”"+”";
    var newTR = document.createElement(’TR’);
    newTR.innerHTML = textString;
    ni.appendChild(newTR);
    }

    // –>

    Add Milestone

    I have additional rows with the same td already i want to add more.

    I have been pulling my hair out doing this!

  76. audienceone

    Is there a full working code for this one. I mean a sample implementation using a form and form validation as well.

  77. Vani Bandargal

    Any body knows how to access dynamicaccly added html elements in Javascript?
    First I add some input text elements on client side on click of “Add Row” buton which is working fine.
    Now I need to validate the value entered in those new form fields before submitting the form.

  78. Jon

    Thanks for the script. I need to dynamically add some plain text and some text areas like:

    Label 1: Textbox1
    Label 2: Textbox2

    How can I do that? The script let me add textbox and seems like they are all on the same line. Any help will be appreciated.

  79. Simon

    Hi,
    I’ve used your script in my web application and it works a treat in IE, but when i use the script in FF it still adds the correct content but as the screen grows vertically downwards the elements i am adding render over the top of the containg table. in IE the containg table is steched to fit in the extra content, Any body else had a problem like this

  80. Kris Randall

    Hi Dustin,
    Your probably sick of hearing it by now but you have done a fantastic job with this example.
    Thanks so much.

  81. Solie

    Hello,
    I’m trying to add textfields dynamically to a form. innerHTML is read only. So is their a way to add a form element dynamically?

    Thanks

    Solie

  82. jithendar

    A big Thank you to Dustin! from another javascript hater ;-)

    I’ve implemented dynamic Text Box’s using your code,Could you give me a few pointers as to how i could grab the value of each Text Box

    thank you
    jithendar

  83. Kiril Cvetkov

    hey Dustin,
    Thank you so much for that code. it helped me a lot.
    At first place I was having some problems with it, but with few switches on commas at the ‘innerHTML’. it is working perfectly now.
    and I changed the remove code a little bit.
    here is what I did:

    function addElement() {
    var ni = document.getElementById(’myDiv’);
    var numi = document.getElementById(’theValue’);
    var num = (document.getElementById(’theValue’).value -1)+ 2;
    numi.value = num;
    var newdiv = document.createElement(’div’);
    var divIdName = ‘my’+num+’Div’;
    newdiv.setAttribute(’id’,divIdName);
    newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! Remove the div “‘+divIdName+’”‘;
    ni.appendChild(newdiv);
    }
    function removeElement(divNum) {
    var d = document.getElementById(’myDiv’);
    d.removeChild(divNum);
    }

    I’m programing in php, I don’t know does it matter.
    Thanks again.

    best regards,
    kiril

  84. Kiril Cvetkov

    I’ll post it again ’cause it’s not seen very good at my last post. I’ll replace the “” characters with “*”
    newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! *input name=”field’+num+’” type=”text” value=”" /**a href=”#” onclick=”removeElement(’+divIdName+’)”>Remove the div “‘+divIdName+’”*/a*’;

    thanks again

  85. gagan

    me so horny at this piece o code….

    i like it a laaaaaaaaat
    thanks !!

  86. feanor

    i’m trying to do something similar but i’m creating a textarea dynamically and trying to get at what the user typed in it in my vbscript… so far i had no luck here, the code

    function input(obj){

    var radioName = obj.getAttribute(”name”);
    var hiddenName = ‘txt’ + radioName;
    var hidden =document.getElementById(hiddenName);
    var newText = document.createElement(’textarea’);
    newText.setAttribute(”id”, “textbox”);
    hidden.parentNode.appendChild(newText);

    }
    what i’m trying to do is insert a textarea next to the hidden input. the function is called when a radio button is clicked. so far so good, i see the textarea. now, in my vbscript i want the text in the textarea, but it seems there is no way for me to access it. here’s what i tried…

    any ideas?

  87. Dan

    The code is wonderful, thank you so much. The only road block i’ve ran into is addind floating (float:left) div’s in a container.

    If the static divs are 90 pixels high (not set, just end up that high) and then i use addElement() to add a new div with an img tag in the innerHTML, the new DIV’s are only as high as the previous.

    This isn’t an issue in IE, only FIREFOX. I also have a function that adjusts the height of every DIV after the addElement has done it’s thing, but still no luck.

    Any ideas?

  88. shridhar

    on click radio button we get text box using java script

  89. mike

    Hey all,

    This is great.

    One issue for me is though I am creating the element, in FF (my best friend) the append ignores WHERE the div is in the code and displays it at the TOP of the page no matter what.

    This is obviously a major issue as you want the content to be displayed where ever you wish.

    Has anyone had this issue, can anyone help?

    ex:

    … code …

    … code …

    but displays as:

    … code …

  90. John

    Thanks a bunch for the tutorial. Great stuff!

  91. Vetra

    Nice article, very helpful and it works :)

  92. Ashley

    Instead of using a div element, I would like to use . I’m also wanting to dynamically add a user control into the column.

    How would I go about doing this?

    Any help is much appreciated! Thanks :)

  93. Ashley

    sorry, I would like to dynamically create a new row and column.

  94. Celsol

    Great script, been looking for something like this for a few days now, big thank you to Dustin Diaz for sharing knowledge..

  95. Chris

    Hey guys,

    I am using this technique to clear html file input controls. As all might know, file input controls do not allow that the value attribute is cleared (for security reasons) so I do this by deleting the current input control and create a new one identical to the previous (when a clear button is clicked). Everything works fine, but the only thing that bugs me is that the newly created input control is not being displayed with its assigned class attribute (css), therefore not looking like the other one. Is there a reason for this? I would appreciate a lot your help.

    Thanks in advance!

  96. sreejith

    very good

  97. Akshay

    Many thanks to you. I am new to programming and I was yesterday gvn this task to add/remove bunch of controls by client-side scripting. It was wonderful. The way gvn abv worked quite well.
    Thanks again.
    Best regards
    -Akki

  98. Justin Hambleton

    Anyone know how I would re-index the added elements? For example, each new element increases the index by 1, however when I remove an element, it doesn’t refresh the index. For example: I add four elements (Item #1, Item #2, Item #3, Item #4). I decide to delete Item #2, leaving Item #1, Item #3 and Item #4. I would like Item #4 to become Item #3 and Item #3 to become Item #2. Hopefully this makes sense.

  99. Chadwick

    function removeElement(divNum) {
    var d = document.getElementById(’myDiv’);
    d.removeChild(divNum);
    }

  100. Chadwick

    oops on the last post…. I can’t get the remove function to work in FF. Works just fine in ie but I get a “my1Div is not defined” error via the javascript console…

    function removeElement(divNum) {
    var d = document.getElementById(’myDiv’);
    d.removeChild(divNum);
    }

  101. Chadwick

    Well I figured it out. In ie when calling the removeElement() function, single quotes aren’t required. In ff they are. So when I created my innerHTML I just had to make sure that my divIdName was in quotes like so…

    … onclick=”removeDriver(\”+divIdName+’\');” />
    I also reworked the addElement() function to provide a little less code.

    function addCar()
    {
    var ni = document.getElementById(’myDiv’);
    var numi = document.getElementById(’theValue’);
    var num = Number(numi.value);
    numi.value = ++num;

    var newdiv = document.createElement(’div’);
    var divIdName = ‘myDiv’+num;
    newdiv.setAttribute(”id”,divIdName);

    newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! Remove the div “‘+divIdName+’”‘;
    ni.appendChild(newdiv);
    }

  102. Gareth Stirling

    Is there a way to use the code in a drop down menu?

  103. Xavier

    Hey Gareth Stirling !!

    Here is the code for select object:

    selElement = document.createElement(’select’);
    selElement.setAttribute(’name’, ‘field_name’);
    var o = document.createElement(”OPTION”);
    var t = document.createTextNode(”Select Options”);
    o.setAttribute(”value”,”0″);
    o.appendChild(t);
    selElement.appendChild(o);

  104. Mark

    ————————
    Hi,

    i was searching for adding an event to a dynamically created element and got to your website.

    Is there any way to add a event dynamically(ex:onClick=”openWin(xxxxx,xxx);”) to the dynamically created element?

    I am trying to get it work and no luck so far.

    thanks Sravan

    Sraven, I’m having exactly the same problem. It works fine in netscape, firefox, but IE refuses to pick up on the fact i’ve clicked on an element I’ve just added that has a new onclick event… I’m doing something with dynamic ratings for articles, code as follows:

    objectToAppend = document.createElement(”img”);
    objectToAppend.setAttribute(”src”,”images/starfilled.gif”);
    objectToAppend.setAttribute(”onclick”,”javascript:rate(” + starnum + “,” + articleid + “);”);
    objectToAppend.setAttribute(”id”,”article” + articleid + “ratingstar” + starnum);
    d.appendChild(objectToAppend);

    Any ideas from anyone on how to get this working in IE?

    ———————-

    Hi, everyone:

    I was having a similar problem as the code above. Here’s what I did to get it to work in both IE and Firefox. I changed the line:

    objectToAppend.setAttribute(”onclick”,”javascript:rate(” + starnum + “,” + articleid + “);”);

    to:

    objectToAppend.onclick = function() {rate(starnum, articleid);};

    Hope this helps anyone who finds this (It drove me nuts for over a day :) )

    Mark

  105. Ed

    Thanks for the great tutorial, and thanks to Chadwick for the quote solution!

  106. Joseph Szymbabwe

    Hey, I have this div on my site put there dynamically by my free hosting provider. Is there a way to remove using derrivitives from this script? I tried to find it but I’m not that ‘Fluent’ in DOM and Javascript. The script that the free hosting provider puts is located at http://gig4free.com/freesites/include.js. The DIV i’m trying to delete is called “divStayBottomLeft” (subtle isn’t it :-) ). Thanks for your enormous help!

  107. Raman Basu

    It sounds good to manipulate HTML element using javascript, but what about dynamically generated dropdowns which are nested and dependent ????

    Any Idea?

  108. Oliver Jackson

    Joseph (106)

    what about something like this

    function noDivBottomLeft() {
    var noStay = document.getElementById(’divStayBottomLeft’);
    noStay.parentNode.removeChild(noStay);
    }

    then use a

  109. Oliver Jackson

    … continued

    use a onload=”noDivBottomLeft()” in body tag

  110. Ceejay

    Cool !!!

    Using it to clean up dynamically created AJAX “windows” when closing them.

    Keep them comming.

  111. Adriaan

    Very cool script! Thanks alot!

  112. Adriaan

    I’m using the script to create 2 html select inputs, which works great btw, I get an error however when trying to get the POSTed values in Firefox. They are received 100% in IE, but nothing that was created dynamically is POSTed through in Firefox.

    Does anybody have any idea why?

    Please help!

    Thanks

  113. Sujit

    Thanks a lot for it. hope its gng to work for me.

  114. Kim Steinhaug

    Hmm, sems alot of users are having problems with Firefox and dynamically added elements. Seems that when you submit the form added elements are not included in the submit. Needless to say I am having the exact same problem, and only in Firefox. It has nothing to do with this example, however googling landed me here so I share my agony as noone has answered the problem yet.

    I am also adding the elements with innerHTML, maby I need to create the elements more correctly with the DOM - maby that will work. I will post my findings.

  115. Kim Steinhaug

    Hmm, I know did a test with adding all new fields correctly with the DOM and createElement() method. Same problem, Firefox doesnt recognize the dynamically added fields. Looks like I’m going for a “doesnt work with Firefox” sollution… hmm…

  116. Kim Steinhaug

    Alrighty, the sollution is at hand. Seems that a blast from the past gave me this problem. In the old days before CSS we usually defined a form like this to avoid troublesome padding and margins :

    This is not validating looking at the nesting of the elements, so if we do it correctly like this :

    Firefox will work, naturally it works anyways in IE because of the nice error handling we sometimes loose our heads over…

  117. Kim Steinhaug

    OK, seems the parser chopped away the code, lets do some pseudo code again :

    table
    form
    tr
    td

    /td
    /tr
    /form
    /table

    This doesnt work, this does :

    form
    table
    tr
    td

    /td
    /tr
    /table
    /form

  118. Amrita

    Hi,
    I am looking for code to add a drop down box dynamically to a particular position and not to the end of the form….
    i have used the following javascript code:

    var newsel= document.createElement(’select’);

    newsel.setAttribute(’id’,newSelect);
    var emptyOption=document.createElement(”option”);
    emptyOption.setAttribute(”value”,”");
    emptyOption.innerHTML=”Hi i’m a new box”;
    newsel.appendChild(emptyOption);

    form.appendChild(newsel);

    the above code works fine,but appends the dropdown to the end of the form (as i’ve used form.appendChild) but the dropdown box isnt even displayed if i dont use form.appendChild
    could anyone help….

    thanx in advance…

  119. shyam

    this is just what i was looking for… Very cool script! Thanks alot. big thank you to Dustin Diaz for sharing knowledge..

  120. Ali

    Thank’s, it’s a great article.

  121. Upratovanie

    Hi people,
    it’s 5:30 am. I’m just having a cup of coffee and I just came across this excellent and useful article. I must say to you, Dustin: Good job!

    I was searching for some JS-based function which allow me to add new objects. And this article resolved this my problem! Thanks, Dustin.

  122. Yukti

    hi
    even i have problem with FIREFOX not posting the values well.A solution could be creation of an array in javascript , with index of the array as controll name and the values be the one added by the user.Setting the array to the hidden field and checking on the next page after POSt. Hope this works .. sooon will come with the code

    regards
    Yukti

  123. Jeswin

    i used your code to add an additional table (form) when a button is clicked. i have many textboxes in it, i need to append value/id to each textbox when it gets created, so that each textbox has a unique id.. i passed the value

    let me know if this will create a unique id each time when the table gets created?

  124. Tbroas

    Great code, thanks for providing it. I have question. I am using it to dynamically create input (text) fields so that users can add rows to a table and then type text into the field. I can get this to work fine:

    function addEvent()
    {
    var ni = document.getElementById(’myDiv’);
    var numi = document.getElementById(’theValue’);
    num = (document.getElementById(”theValue”).value -1)+ 2;
    numi.value = num;
    num = num - deleted;
    var divIdName = “my”+num+”Div”;
    var step =”step”+num;
    var newdiv = document.createElement(’div’);
    newdiv.setAttribute(”id”,divIdName);
    newdiv.innerHTML = “Step: “+num+” “;
    var x = “Step: “+num+” “;
    alert(x);
    newdiv.innerHTML +=” “;
    ni.appendChild(newdiv);
    }

    I want to be able to set the value of these new input fields, but I can’t seem to get it to work. I can get it to work on text input fields that are not created with “createElement”, but for some reason I can’t get it to work on input fields created with the code provided. Any ideas why? Is there a way to append the the new input field?

  125. Chris

    This helps me out greatly. This is very much appreciated.

  126. CraigM

    Yukti - don’t worry about the hidden controls.

    Look at what Kim said above. She nailed it. I was having this problem too and as she did I had the “old school” habit of nesting my form elements inside my TABLE elements to prevent extra padding, which is a no-no and Firefox does not like it.

    Make sure your page elements are nested properly (FORM,TABLE,TR,TD,/TD,/TR,/TABLE,/FORM) and I think you will find it works great!

    As for the evil padding, I believe there is a way to set this using CSS these days - I will look for this next.

  127. tulasi

    Very thanks to Mark for giving the code that
    how to add event dynamically to dynamically added control

  128. Adriaan

    Everybody that gets the problem with firefox NOT receiving the POSTed values of the dynamically created inputs. It is because your tag is within a or another similar tag. Put your form tags right on the outside and it will work!

    Hope this helps you!

  129. Adriaan

    Everybody that gets the problem with firefox NOT receiving the POSTed values of the dynamically created inputs. It is because your form tag is within a table or another similar tag. Put your form tags right on the outside and it will work!

    Hope this helps you!

    Sorry for the double post, but my tags was removed in the first post.

  130. mike

    This is a great tool. I want to use it with a drag n drop sript I have. the script needs to know what the name of new id’s are as they are created. for some reason when I inter my1Div, my2Div…… the drag n drop script isn’t recognizing those ids. Any ideas. am i getting the new ids right?

  131. Jon

    i’m having the same problem as Chadwick with the “my1Div is not defined” error. i changed it to single quotes but i still get the same error. This is what i have:

    newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! Remove the div ‘+divIdName+’

    the page adds ok, but it won’t remove them. any help would be appreciated! thanks!

  132. Jon

    newdiv.innerHTML = ‘Element Number ‘+num+’ has been added! href=”javascript:;” onclick=”removeElement(’+divIdName+’);”>Remove the div ‘+divIdName+’/a’

    hopefully now the code can be viewed, i took out the link tag

  133. Jacob

    Hi Mark,
    Thanks a lot for sharing the knowlege on dynamically adding and removing html elements.Hope you will continue the same

  134. Bjarne

    Nice article… just what I was looking for.

    A note thou: You dont need a hidden div!

    document.body.appendChild(newDiv);

    Will add you new div directly to the body of your document. I especially use it with position:absolute, where I move my div’s around.

  135. Monkey

    Nice to see people using this stuff, thanks for the code Dustin.

    small suggestion :
    How about just passing the element or the element’s id to the function to remove, then use the .parentElement property instead of trying to work out the specific container for each item.

    function RemoveScheduleItem( item )
    {
    item.parentElement.removeChild(item) ;
    }

    or use getElementById() if you can only pass in the id rather than the element itself.

    Is this valid ? seems to work but then i only have to support MSIE for my current project.

    Mike

  136. Tom Bender

    I’m a server-side guy just recently biting the bullet on Javascript. Ughhhh

    Your article came in particularily handy for my upcoming demo at Siemans AG.

    Muchas Gracias!

  137. Graham B

    Mike,

    I’ve always used the parentElement.removeChild trick and it works perfectly across browsers. Much neater than storing ids/references in variables.

  138. Sven

    Hi,

    Great article, this really is what I was looking for.

    But I’m stuck with a question.
    Why wouldn’t you use a global var instead of a hidden inputfield to count die id’s?

  139. Paresh Prajapati

    Really very very usefull….
    It really contain good help for managing dynamic html controls with javascript.

    GREAT.

  140. Anu

    Hai,

    i want to make a button’s visible property false by using a javascript function.i mean i want to create a javascript function in .aspx file. in that function i want to write code to make a button’s visible property false and i want to call this function in another button’s onclick event from .aspx file itself.how can i do?
    please give me a reply?????????….

    Anu

  141. Margus

    I would use CSS, to declare invisable state, and call it with JS:

    .nhtamatu { visibility:hidden }

    Hide the button, with a Click on ME.

  142. Margus

    would use CSS, to declare invisable state, and call it with JS:
    [code]

    .nähtamatu { visibility:hidden }

    Hide the button, with a Click on ME.

    [/code]

  143. Margus

    I would use CSS, to declare invisable state, and call it with JS:

    <script language=”javascript”><!–
    function peida(id){document.getElementById(id).className=’nähtamatu’}//–>
    </script>

    <STYLE>
    .nähtamatu { visibility:hidden }
    </STYLE>

    <P onclick= peida(’n')>
    Hide the button, with a Click on ME.
    </P>

    <input type=”button” value=”Nupp” id=”N”>

    DMN CODE BANNER

  144. Raghavendra U

    Awesome, i can’t tell in words how simple it was how it helped me a lot, Thanks a Lot Sir Thanks a Lot :
    :-)

  145. matthew

    is there a way i could get the divs content from an external file, with the external file it uses is called from the link that calls the creation of the div?.

  146. Mr. Gundu

    Hi. I’m using this code to display a list of input from a user. Problem is that it adds the new input below the old stuff so it looks like this:
    Old
    Old
    New
    What I would like for it to do though is add to it like this:
    Old Old New
    Any help would be great appreciated. Thanks for the starting point with this code Dustin. It was fantastic to find it.

  147. Heidi

    is it possible to remove only the elements in a div

  148. Nick Marinho

    This don’t work here, FIrefox 1.5, Opera and too not work in IE6.

    This is my code:

    function makeFile() {
    var ni = document.getElementById(’divTexts’);
    var numi = document.getElementById(’theValue’);
    var num = (document.getElementById(’theValue’).value -1)+ 2;
    numi.value = num;
    var newdiv = document.createElement(’div’);
    var divIdName = ‘file_’+num+’_';
    newdiv.setAttribute(’id’,divIdName);
    newdiv.innerHTML = ‘Nome:  Email:   ‘+divIdName+’‘;
    ni.appendChild(newdiv);
    }

    function makeInput() {
    var inp = document.getElementById(’divFiles’);
    var numi = document.getElementById(’theValue’);
    var num = (document.getElementById(’theValue’).value -1)+ 2;
    numi.value = num;
    var inpname = ‘text_’+num+’_';
    var newinput = document.createElement(’input’);
    newinput.setAttribute(’type’,'file’);
    newinput.setAttribute(’id’,inpname);
    newinput.setAttribute(’name’,'file[]’);
    newinput.setAttribute(’onclick’,'remElement(divFiles,’+inpname+’)');
    newinput.setAttribute(’style’,'width:100%;’);
    inp.appendChild(newinput);
    }

    function remElementOld(campo,numero) {
    var d = document.getElementById(campo);
    d.parentElement.removeChild(numero);
    }

    function remElement(campo,numero) {
    var d = document.getElementById(campo);
    alert(campo + ‘= ‘ + numero);
    }

  149. mmp

    Hai!

    How does GMail adds the file Input fields dynamically when composing a mail.

    Yahoo does it by having 50 file Input fields out of which 5 are displayed and 45 are hidden initially and later displayed on clicking Attach More Files button.

    Usually most of the known browsers doesn’t support dynamic addition of file Input fields(for security reasons). But I wonder how GMail manages this issue.

    Am aware that GMail is built on AJAX, but how do they handle this file Input field issue.
    Can any one help me out? I just want the logic behind it.

    Thanks in advance.

  150. glen

    I apologize if this topic has already been covered, but I need a little help getting file input working… thought I had it but can’t get it to work.

    Reply 149 sheds a little light on the fact that maybe what I’m trying to do basically won’t work the way I’m trying to do it? Here’s my code…

    Remove Attachment“;
    ni.appendChild(newdiv);
    }

    function removeEvent(divNum)
    {
    var d = document.getElementById(’myDiv’);
    var olddiv = document.getElementById(divNum);
    d.removeChild(olddiv);
    }

    If a file needs to be included (such as a logo, word document, etc)attach it here with the Browse button.

    Add Another File

    Basically the first file they put in the file form will be named ‘uploadedfile’ and then when they click “Add Another File” that one will be ‘uploadedfile1′ then ‘uploadedfile2′ etc. Whenever I try and use the script it only emails the first file. Any ideas?

    Looks like it should work but are there security settings that don’t allow this?

    Thanks

  151. glen

    here’s the code again sorry about the double post.
    angle brackets are replaced w/ square ones.

    The add event function…

    var ni = document.getElementById(’myDiv’);
    var numi = document.getElementById(’theValue’);
    var num = (document.getElementById(”theValue”).value -1)+ 2;
    numi.value = num;
    var divIdName = “my”+num+”Div”;
    var newdiv = document.createElement(’div’);
    newdiv.setAttribute(”id”,divIdName);
    newdiv.innerHTML = “[input name=\”uploadedfile”+num+”\” type=\”file\” size=\”50\” /] [a href=\”javascript:;\” onclick=\”removeEvent(\’”+divIdName+”\’)\”]Remove Attachment[/a]”;
    ni.appendChild(newdiv);

  152. Vishal

    Apart from my comments, I have a tiny question. Can I use the same logic to dynamically update structure of a table?
    Thanks

  153. sairam

    I cant get any output with this code

  154. Godfrey

    Hello, I need some help with some javascript coding.

    I am displaying some data using a dynamic table created by coding below.The coding below adds one row with 6 cells to the table. The last column in the table contains a button to delete the row.

    //==============================FUNCTION ADD NEW ROW=============================
    var count = “1″;
    var GrandTotalPrice=0.00;
    function addRow(in_tbl_name)
    {
    var sel = document.getElementById(”txtStockCode”);
    var sel2 = document.getElementById(”txtStockName”);
    var sel3 = document.getElementById(”txtStockQuantity”);
    var sel4 = document.getElementById(”txtStockPrice”);
    var sel5 = document.getElementById(”txtTotalPrice”);

    if(document.frmsin.txtstockcode[document.frmsin.txtstockcode.selectedIndex].text ==’Select Stock Code’ || document.frmsin.txtStockQuantity.value ==”" )
    {
    alert(’Please Fill in All Data’);
    return;
    }
    else
    {

    var tbody = document.getElementById(in_tbl_name).getElementsByTagName(”TBODY”)[0];
    // create row
    var row = document.createElement(”TR”);

    // create table cell 1
    var td1 = document.createElement(”TD”)
    var strHtml1 = ” ” + sel.options[sel.selectedIndex].text + “”;
    td1.innerHTML = strHtml1.replace(/!count!/g,count);
    td1.setAttribute(’id’, ‘td1_’ + count,0);

    // create table cell 2
    var td2 = document.createElement(”TD”)
    var strHtml2 = “” + document.frmsin.txtStockName.value + “”;
    td2.innerHTML = strHtml2.replace(/!count!/g,count);
    td2.setAttribute(’id’, ‘td2_’ + count,0);

    // create table cell 3
    var td3 = document.createElement(”TD”)
    var strHtml3 = “” + document.frmsin.txtStockPrice.value + “”;
    td3.innerHTML = strHtml3.replace(/!count!/g,count);
    td3.setAttribute(’id’, ‘td3_’ + count,0);

    // create table cell 4
    var td4 = document.createElement(”TD”)
    var strHtml4 = “” + document.frmsin.txtStockQuantity.value + “”;
    td4.innerHTML = strHtml4.replace(/!count!/g,count);
    td4.setAttribute(’id’, ‘td4_’ + count,0);

    // create table cell 4
    var td5 = document.createElement(”TD”)
    var strHtml5 = “” + document.frmsin.txtTotalPrice.value + “”;
    td5.innerHTML = strHtml5.replace(/!count!/g,count);
    GrandTotalPrice = eval(GrandTotalPrice) + eval(document.frmsin.txtTotalPrice.value)
    document.frmsin.txtGrandTotalPrice.value = GrandTotalPrice
    td5.setAttribute(’id’, ‘td5_’ + count,0);

    // create table cell 6
    var td6 = document.createElement(”TD”)
    var strHtml6 = “”;
    td6.innerHTML = strHtml6.replace(/!count!/g,count);
    td6.setAttribute(’id’, ‘td6_’ + count,0);

    // append data to row
    row.appendChild(td1);
    row.appendChild(td2);
    row.appendChild(td3);
    row.appendChild(td4);
    row.appendChild(td5);
    row.appendChild(td6);
    // add to count variable
    count = parseInt(count) + 1;
    // append row to table
    tbody.appendChild(row);
    document.frmsin.txtStockQuantity.value =”"
    document.frmsin.txtTotalPrice.value=”"

    }
    }

    //======================FUNCTION DELETE ROW=====================================
    function delRow()
    {
    //var current = window.event.srcElement;
    var current = window.event.srcElement;
    //here we will delete the line
    while ( (current = current.parentElement) && current.tagName !=”TR”);
    current.parentElement.removeChild(current);
    // var allTDs = document.getElementsByTagName(”td”);
    //var firstTD = allTDs.item(0).id;
    //var lastTD = allTDs.item(allTDs.length-1).id;
    //var str = “# of table cells: ” + allTDs.length + “\n”;
    //str += “First TD: ” + firstTD + “\n”;
    //str += “Last TD: ” + lastTD;
    //alert(str);
    }

    //========================END FUNCTION==========================================

    I have created a single textbox below to show the Grand Total Price (TotalPrice1+ TotalPrice2 + so on…)Everytime the function addRow fires, the Grand Total Price will be updated with this statement.

    GrandTotalPrice = eval(GrandTotalPrice) + eval(document.frmsin.txtTotalPrice.value)
    document.frmsin.txtGrandTotalPrice.value = GrandTotalPrice

    However when I delete a row, the value of Grand Total Price textbox stays the same and not updated. How can I update the Grand Total Price value when I delete a row? Hopefully someone canhelp. Thanks.

  155. SandiPawar

    Hi, I have added div dynamically to parent div using above code. IT is added successfully but when I view source code by right clicking on page. It is not showing me newlly added div elments anywhere on page. Hence I am not able to do any operation with them. Can any one please help me on this. I have want to move(draggable) these newly added child div elements to some other place on page. For moving elements I am using some third party javascript library. But is it because that elements are not get added properly they are not availble for further operation. Please reply soon.It’s very urgent. Thanking you, Sandi

  156. m.k

    Thanks for this.

  157. mihai

    Hi,
    I am having this prblem on IE6 with the following code:

    var form = document.forms[0];
    var tbl = document.getElementById(”table6″);
    var row = tbl.insertRow();

    var cell0 = row.insertCell(0);
    var checkField = document.createElement(”input”);
    checkField.setAttribute(”type”, “checkbox”);
    checkField.setAttribute(”name”, “checkItem”);
    checkField.setAttribute(”id”,”checkItemNew”);
    cell0.appendChild(checkField);

    var cell1 = row.insertCell(1);
    var scCd = document.createElement(”input”);
    scCd.setAttribute(”type”, “text”);
    scCd.setAttribute(”name”,”scoreCodeNew”);
    scCd.setAttribute(”id”, “scoreCodeNew”);

    //***********************************************************
    //scCd.setAttribute(’onChange’,’saveChanges()’);
    //scCd.innerHTML = ” onChange=\’javascript:saveChanges();’\”;
    //scCd.onChange = saveChanges();
    //***********************************************************

    cell1.appendChild(scCd);

    It looks that I have the same problem like others to call on “onchange” event of the new created element this method saveChanges(). I tried all the above but with no luck.
    Please give me a hint !!!! Regards !

  158. mihai

    This line is working now !!!

    scCd.onchange = saveChanges;

    Event Name must be lower case !!!
    I hope it helps others !!!

    Mihai

  159. Salman

    THANKS!
    Great script and very usefull in my current project, I had a little problem with firefox not getting submitted variables from dynamic fields but Adriaan’s idea worked, just moved [form] tags outside the tables and it started working (Y)

    * Salman likes it!

  160. John

    Reply on:

    SandiPawar
    October 12th, 2006 at 7:50 am

    Hi, I have added div dynamically to parent div using above code. IT is added successfully but when I view source code by right clicking on page. It is not showing me newlly added div elments anywhere on page. Hence I am not able to do any operation with them. Can any one please help me on this. I have want to move(draggable) these newly added child div elements to some other place on page. For moving elements I am using some third party javascript library. But is it because that elements are not get added properly they are not availble for further operation. Please reply soon.It’s very urgent. Thanking you, Sandi

    ###########################################################################

    Hi Sandi

    I had the same problem. The only way to actually see what items have been added, is to add the values of the added items to an extra control (listbox), then set a textbox = to the listbox. Then you will be able to get the values. This is great for when you are using aspx because you will be abe to get the values in your aspx code (baring in mind that you must use a server side textbox).

    Hope this helps.

    Cheers
    John

  161. Tvorba stránok

    Great article!! It helped me… thanks, Dustin

  162. kevin

    Thanx mate,

    newdiv.innerHTML saves me. Nice tutorial dude.

  163. Matthew

    Hi,
    It was a chance (and some googling) to bump into this page! I was working on a new user interface problem where I had to create dynamical form elements.
    Thank you for your contribution.

  164. Rob

    This is a great solution. Thanks!! This cut my code by more than half and solved the problems associated with it.

  165. Keith Greer

    Great article, very useful. Will be back here again. Thanks!

  166. Mohammed

    It is a great code. I implemented it.
    It add fields fine, but when I remove, it removes based on the ID correctly, but after fraction of a second it deletes all the elements.
    Any ideas.

  167. Mohammed

    Never mind, I got it to work.

    Thanks,

  168. Mohammed

    Any ideas how to get the code to work in IE, it works fine in Firefox.
    The code I am using is the same as the code provided at the very beginning of this page.

    Thanks,

  169. donovan

    Yo, like your code. I’m adding a version of it to my library. I’ve also included it here for your edification (it’s brief.. you might like it)

    
    /*this is a general purpose function that keeps you from having to type 'document.getElementById'.. saves time and typing. I use it's like EVERYWHERE*/
    function el(inID) {
      return(document.getElementById(inID));
    }
    
    /*this function creates an element, appends it to the parent, and then returns it so you can set it's innerHTML, style and other attributes.  You never know what you're going to need to do after creating one. */
    function addElement(inElementType, inElementID, inParentID) {
      newEl = document.createElement(inElementType);
      newEl.setAttribute('id', inElementID);
      el(inParentID).appendChild(newEl);
      return(newEl);
    }
    
    /*This last function removes the element from it's parent, even without you having to know who it's parent IS.  I considered calling it 'popElement' because it returns the removed element in-case you need it somewhere... 'removeChild' doesn't really delete the element anyway, so you may as well be able to keep an handle on it if you want to. */
    function removeElement(inID) {
      oldEl = el(inID);
      parentEl = oldEl.parentNode;
      return(parentEl.removeChild(oldEl));
    }
    
    

    I Hope you like the code!

    Donovan

  170. satish

    Hi ,

    My name is satish , I am new to Java Script ., Regarding help on Java Script..,

    When ever on clicking the Attach files Label a new pop up window comes up

    with Text Area Having Drag and Drop Files Facility and Buttons (Browse and Remove)
    and OK and Cancel Buttons. Now all Buttons are Enabled

    According to my requirement , First Remove button is Disabled(when first pop up time)

    Second one . when we perform drag and drop a file in text Area , Remove should be Enabled .

    If you have any idea and code please send me

  171. saurabh

    I am working in HTML and i have created a select box and how can i delete a element/item from a select box.

  172. saurabh

    Hi
    I am saurabh and i am new to HTMl and Java script can any one tell me that how can i send mail through outlook express with an attachment using HTML or ASP.net

  173. Otváranie trezorov

    I was searching for solution like this for hours and finally I’ve got it! Thanks Dustin, you helped me :)

  174. DuGiNTHaMuD

    Not what I had in mind, as to how I was gonna go it, but it works great for what I needed. THANKS ( Open skull, stir grey matter, does wonders. )

  175. Net_Giant

    I used something similar in a page at work. I ran across a problem with IE 6 however. Everything worked as expected when the form was submitted. The problem showed up when the user hit the back button – the dynamically created controls were gone. FireFox displayed the dynamic controls just as they were before the form was submitted. Any ideas?

  176. dharmesh

    it was really very informative article. it will help me lot.thanks….

  177. spiritz

    thx so much, i decide to use this after picking many other ways ;)

  178. Jason

    Hi.. Great Function Dustin.

    What I need to do is something similar, except I need to is pull some
    values from text fields generated.

    newdiv.innerHTML = "";

    I thought maybe using..

    document.frmAnalysis.TestBlah123[0]

    would work, but I get “undefined”. Is there a way to even do that?

  179. George

    Awesome. Very helpful and simple for what I needed. Thx.

  180. Guest2#%%$&%^&#$%

    I post just to say thank you to -Kim Steinhaug- for posting the solution for that dynamic content not submitting problem. Saved me from a lot of tests and headaches THANK YOU

    And remember kids! Never nest tags inside of table tags! just set padding and margin of form tag to 0 to avoid spacing!

  181. chochis

    And now, my two cents:
    Have you seen what happens in IE6 (mainly) when you do an appendChild? :-) HTTP REQUEST FOR THE DOCUMENT! LOL! if you do it 20 times, it will do it 20 times!
    In FF it just do it once (what i have seen). I have to keep testing! Im going to rewrite the appendChild function with innerHTML and see what happens! :-O

  182. Gyan

    How to set background as selected of a Asp.Net2.0 TreeView node using JavaScript when user clicks on a node?

  183. sangeeth

    i have a requiremnt in my project.i need to add html elements dynamically.after wrting data..into the rows i have update them in to my database(mysql)…how cani reference the dynamically created data and update in to the table.

  184. Mehul

    Hi…
    Good tips… Thanks…
    And does anyone knows answer for above question by Sangeeth. I’ve same kind requirement too….
    Thanks.

  185. Ankur

    as we can set attribute of any HTML element dynamically
    can we set EVENT of HTNL element dynamically with javascript
    like onclick event i want to call cancel() function.
    i can do this thing in HTML easily but how i can set event of a HTML butoon
    dybamically using javascript.

    please whatever you know let me know.
    it’s urgent.

    thnks

  186. Ankur

    as we can set attribute of any HTML element dynamically
    can we set EVENT of HTNL element dynamically with javascript
    like onclick event i want to call cancel() function.
    i can do this thing in HTML easily but how i can set event of a HTML butoon
    dybamically using javascript.

    please whatever you know let me know.
    it’s urgent.

    if possible then send replay on this mail id also
    anks_ce@yahoo.com please

    thnks

  187. theguyofdoom

    Hi,

    Can you halp me? I can’t make sense of my problem:

    I have to add a number of textboxes (the number comes from a textbox) when the box is changed. I made the folowing code to Dustin’s example:

    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <script language="JavaScript" type="text/javascript">
    <!--
    
    function addEvent(times)
    {
    for (e=1; e <= times ; e  )
    var ni = document.getElementById('myDiv');
    var numi = document.getElementById('theValue');
    var num = (document.getElementById("theValue").value -1)  2;
    numi.value = num;
    var divIdName = "my" num "Div";
    var newdiv = document.createElement('div');
    newdiv.setAttribute("id",divIdName);
    newdiv.innerHTML = '<tr><td></td><td>time ' num '</td><td align="center"> <input type="text" name="textbox' num '"</td></tr>';
    ni.appendChild(newdiv);
    }
    
    //-->
    </script>
    </head>
    
    <body>
    	<input type="hidden" value="0" id="theValue" />
    	<p><a href="javascript:;" onclick="addEvent(addEvent(document.getElementByID('aantalmobieltjes').value));">Add Some Elements</a></p>
    	<input type="text" name="numberoftimes" id="numberoftimes" onchange="addEvent(document.getElementByID('numberoftimes').value)" />
    	<div id="myDiv"> </div>
    
    </body>
    </html>
    

    Ps: Yes, I’m new to JavaScrit. So if I screwed it…

  188. theguyofdoom

    oops, I forgot to delete the link from Dustin’s code, so an comment:

    Ignore the

    <p><a href="javascript:;" onclick="addEvent(addEvent(document.getElementByID(’aantalmobieltjes’).value));">Add Some Elements</a></p>

    code

  189. Jayaprakash

    Thank you for the cool piece of code..its great.

  190. sudeep M

    Kool stuff, really helped me a lot for dynamic content addition and removal.
    Good work indeed.
    Thanks

  191. A to Z of World

    I love java script. Thanks for the inof.

  192. Hetal

    can any1 help me with the above code its giving me error

  193. sangeeth

    i have a row which contains two text boxes and tow list boxes.when i click the add button i should add(append) a row which contains same elemets.please tell me how can i create a listbox or select box dynalically.

  194. jb

    Oopz, here’s the code:

    newdiv.innerHTML = ‘    VERWIJDER DJ    new Ajax.Autocompleter(”dj[]”,”hint[]”,”autocomplete/dj.php”);’;

  195. jb

    I’m trying to combine Dustin’s script with http://wiseguysonly.com/demos/ajax-autocompletion/autocomplete.php

    It works fine in Firefox 2.0, but in IE6 and IE7 the autocomplete field appears, but doesn’t work. Can somebody help my figuring out why? Or is it just possible in Firefox?

    P.S. can you delete the other posts?

    function addDj()
    {
    var ni = document.getElementById('myDiv');
    var numi = document.getElementById('theValue');
    var num = (document.getElementById("theValue").value -1)+ 2;
    numi.value = num;
    var divIdName = "my"+num+"Div";
    var newdiv = document.createElement('div');
    newdiv.setAttribute("id",divIdName);
    newdiv.innerHTML = "REMOVE DJnew Ajax.Autocompleter(\”dj[]\”,\”hint[]\”,\”autocomplete/dj.php\”);”;
    ni.appendChild(newdiv);
    }
    
    function removeDj(divNum)
    {
    var d = document.getElementById(’myDiv’);
    var olddiv = document.getElementById(divNum);
    d.removeChild(olddiv);
    }
    
  196. Rukshan

    Hi guys,
    i got it working.. again it was some thing to do with the ‘newdiv.innerHTML’ code block
    i placed two double quotes in either side of removeElement() function’s parameter like this,

    onclick=removeElement(”‘+divIdName+’”)

    earlier it was like,

    onclick=removeElement(’+divIdName+’)
    (without the double quotes)

  197. Ian

    Thankyou, Thankyou, Thankyou

    I have been slapping my head against a desk for three hours trying to sort this out.

    Great solution, simply put for the stupid people (of which I proudly count myself)

    Cheers

  198. delmoras

    awesome!just what i was looking for!!!

  199. Nate

    I need to create a image upload script that adds a thumbnail, caption text input box, and a delete link for every image that the user selects. Anyone care to help me with that?

  200. Imtiaz

    Hi

    I would like to know how to obtain the tag name of elements that are created dynamically using AJAX and DOM Technologies as these cannot be obtain by simply viewing the source of the page.

    Thanks

  201. Dave

    Hi quick question. I use dom to make a dropdown on the fly and then use ajax to populate that dropdown from an xml file straight away after it creation, but It doesn’t seem to work. If I use a ‘reqular html’ dropdown I can add to it. Can this be done?

  202. Paul

    Thanks a ton Dustin! You should write a book. Also, thanks to Donovan for his solution to delete. This has saved me a ton of time.

  203. Nick

    Aside from the tons of junk replies here…
    I just wanted to send a quick thanks Dustin.
    I needed to dynamically add fields to a form, and this is perfect. Worked flawlessly the first attempt.

    And the reason this page is seeing so much traffic probably is because it’s the 2nd hit on google’s results when I searched for “dynamically add form field” with the 1st hit being completely useless and worthless.

    Thanks again. I think I’ll be bookmarking this site for future references.

  204. Pal

    Thanks very helpful.

  205. Tom

    Hi is possible LIMIT number of new elements? for ex: I want is possible add just 3 text field 0:-)
    thnx for help

  206. David

    This is a new vision of your revove function

    function removeEvent(divNum)
    {
    var d = document.getElementById(divNum).parentNode;