Chris Nizzardini, Salt Lake City Utah, Web Developer Specializing in LAMP+Ajax Since 2006

My Blog

Here is my awesome blog. You can find information on programming, linux, documentation, tips for code and database optimization, my thoughts and rants, and whatever else I feel like sharing. Feel free to contribute to the blog by posting comments and asking questions.
JavaScript and Ajax

appending and creating new elements in javascript

Recently I discovered that using innerHTML can cause problems when you are heavily modifying the DOM via javascript. A co-worker was nice enough to introduce me to the createElement and appendChild methods.

Creating a drop down

var select = document.createElement('select');
select.id='student';
select.name='student';
select.className='fieldGray';
select.style.fontSize='10px';

Creating an input box

var input = document.createElement('input');
input.id='tip_amount';
input.name='tip_amount';
input.className='fieldGray';
input.style.width='30px';
input.onblur=getTip;

Now to append these elements to the DOM

var div = document.getElementById('destinationDiv');
div.appendChild(select);
div.appendChild(input);

Resources
http://developer.mozilla.org/en/docs/DOM:document.createElement
http://developer.mozilla.org/en/docs/DOM:element.appendChild

Related posts:

  1. alter css values dynamically with javascript
  2. looping through form fields in javascript
  3. Doing Math in JavaScript umm…sucks
  4. More JavaScript Array Methods (push and join)
  5. using JSON to pass JavaScript arrays to PHP via Ajax

2 Responses to “appending and creating new elements in javascript”

  1. Greg says:

    Just so you know the select and nput elements will fail in IE, because it won’t get the name you tried to set.

    Your code is fine, but IE has major bugs with createElement and setAttribute.

    See details here:
    http://webbugtrack.blogspot.com/2007/10/bug-235-createelement-is-broken-in-ie.html
    and
    http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html

  2. admin says:

    Damnit I hate that browser. Thanks for the heads up, I’ve got some code to fix now…

Leave a Reply