createElement()

Creator:
Aleon

For DOM, createElement is probably one of the handiest of all methods.

For this tutorial, we will create an image append it at the end of the document.

<script type="text/javascript">
<!--
var nImage = document.createElement("img");
//-->
</script>

Now that we have out created element, let's assign it the 'src' attribute.

<script type="text/javascript">
<!--
var nImage = document.createElement("img");
nImage.src = "http://www.solidsnakedesigns.com/images/smileys/smile.gif";
//-->
</script>

Now, for this tutorial I am just using the ' :smile: ' smilie as an example. This is optional, but it's something that I always like to do. Add a small portion give the newly create image no border.

<script type="text/javascript">
<!--
var nImage = document.createElement("img");
nImage.src = "http://www.solidsnakedesigns.com/images/smileys/smile.gif";
nImage.border = '0';
//-->
</script>

Now that our image is created and out attributes are set, let's append it to the document.

<script type="text/javascript">
<!--
var nImage = document.createElement("img");
nImage.src = "http://www.solidsnakedesigns.com/images/smileys/smile.gif";
nImage.border = '0';
document.body.appendChild(nImage);
//-->
</script>

There you have it :smile: . If you're using createElement to make a lot of objects for appending, then check out createDocumentFragment() by Peter.

Description:
A simple tutorial about 'createElement()'. And then appending it.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options