Wednesday, 23 April 2008

Add AJAX page element

This will be a nice quick tip, simply how to use JavaScript to add a page element. The page element can be anything that you can normally do in HTML.

So how do we use JavaScript to Add a Page Element?

Ok say you want to add a new div element to your page, either on a button click, page load or something else. All you need to do is the following

1.

Add a page element called apagediv as follows

<div id="apagediv"></div>

2. Then just use the code below

<script>

pagediv = document.getElementById("apagediv")
newdiv = document.createElement("div")
pagediv.innerHTML = "Your inner HTML";
pagediv.appendChild(newdiv)


</script>



Click Here






You should have a page element that says Your inner HTML

Lets break it down a bit

  1. document.getElementByID - finds the page element with the specified ID
  2. document.createElement - create a page element, thsi can be any page element, but at this point it is only created in page memory
  3. pagediv.innerHTML - this sets the innerHTML property of the newly created element, again this can be any of the attributes for your element i.e src, style or what ever.
  4. pagediv.appendChild - this actually places your newly created element on the page, as the child of the found pagediv, again this can be any element including the body. But using a div gives slightly better page layout.

Well this ends this little tip.

Now if anyone out there has anything you would like to knwo how to do, just drop me an email and I will post a response on this blog.

Thanks
Sean J Connolly
Visit AJAX Web Development Store



DMS - Document Management, Webmail
BuzzProperties.co.uk - Online Property Sales and Letting



No comments: