Last modified on 25 March 2015, at 14:51

JavaScript/Adding Elements

Previous: Finding Elements Index Next: Changing Elements

Basic UsageEdit

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 UseEdit

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