Adding 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.



  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
 



 

Connect with defaultLogic
What We've Done
Led Digital Marketing Efforts of Top 500 e-Retailers.
Worked with Top Brands at Leading Agencies.
Successfully Managed Over $50 million in Digital Ad Spend.
Developed Strategies and Processes that Enabled Brands to Grow During an Economic Downturn.
Taught Advanced Internet Marketing Strategies at the graduate level.


Manage research, learning and skills at defaultLogic. Create an account using LinkedIn or facebook to manage and organize your Digital Marketing and Technology knowledge. defaultLogic works like a shopping cart for information -- helping you to save, discuss and share.

Visit defaultLogic's partner sites below:
PopFlock.com : Music Genres | Musicians | Musical Instruments | Music Industry
NCR Works : Retail Banking | Restaurant Industry | Retail Industry | Hospitality Industry

  Contact Us