JavaScript/Adding Elements
Previous: Finding elements Index Next: Changing elements

Basic Usage

Using the Document Object Module we can create basic HTML elements. Let's create a div.

var myDiv = document.createElement("div");

What if we want the div to have an ID, or a class?

var myDiv = document.createElement("div");
myDiv.id = "myDiv";
myDiv.class = "main";

And we want it added into the page? Let's use the DOM again...

var myDiv = document.createElement("div");
myDiv.id = "myDiv";
myDiv.class = "main";
document.documentElement.appendChild(myDiv);

Further Use

So let's have a simple HTML page...

<html>
<head>
</head>
<body bgcolor="white" text="blue">
  <h1> A simple Javascript created button </h1>
  <div id="button"></div>
</body>
</html>

Where the div which has the id of button, let's add a button.

myButton = document.createElement("input");
myButton.type = "button";
myButton.value = "my button";
placeHolder = document.getElementById("button");
placeHolder.appendChild(myButton);

All together the HTML code looks like:

<html>
<head>
</head>
<body bgcolor="white" text="blue">
  <h1> A simple Javascript created button </h1>
  <div id="button"></div>
  </body>
<script>
myButton = document.createElement("input");
myButton.type = "button";
myButton.value = "my button";
placeHolder = document.getElementById("button");
placeHolder.appendChild(myButton);
</script>
</html>

The page will now have a button on it which has been created via JavaScript.


Previous: Finding elements Index Next: Changing elements

  This article uses material from the Wikipedia page available here. It is released under the Creative Commons Attribution-Share-Alike License 3.0.


JavaScript/Adding_elements
 

Manage research, learning and skills at IT1me. Create an account using LinkedIn to manage and organize your IT knowledge. IT1me works like a shopping cart for information -- helping you to save, discuss and share.


  Contact Us  |  About IT1me.com |  IT Training & References |  IT Careers |  IT Hardware |  IT Software |  IT Books