views:

208

answers:

5

Hi,

I was wondering if it was possible to get Javascript to write some HTML onto the page in a certain DIV.

This is due to the fact, there are certain areas of the site where i don't have access to the markup. But i would like to add a small section there.

For example the container i want to add some html to is <div id="topics"></div>

Is it possible to get Javascript to do this <div id="topics"> <div id="mysection"> </div> </div>

Many thanks!

+6  A: 

This is fairly simple to do, even using plain JavaScript.

var topicsDiv = document.getElementById("topics");
topicsDiv.innerHTML = '<div id="mysection"> </div>';

If you're going to be doing some serious DOM (Document Object Model, i.e. HTML structure) manipulation, however, then I would recommend you look into using the JQuery library. Yet if the task is limited to your question, then normal JavaScript should be fine, as shown above.

Noldorin
innerHTML has "HTML" capitalised, and don't forget to escape your double quotes!
Perspx
@Perspx: Or just use single quotes. :)
Noldorin
+1  A: 

Of course. For example, you can do this using Prototype:

$('topics').update('<div id="mysection"></div>');

The syntax is quite similar for jQuery or another frameworks, and as Noldorin noted, you can do also this without any framework.

Can Berk Güder
Bump on the use of Prototype.
John Bellone
+4  A: 

With simple Javascript (without JQuery or something you could do):

HTML:

<div id="topics"></div>

JS:

document.getElementById('topics').innerHTML = '<div id="mysection"></div>';

Using JQuery you would simply do:

$('#topics').append('<div id="mysection"></div>');
Kevin D.
+1  A: 

You are probably looking for the innerHTML property

document.getElementById('topics').innerHTML = 'whatever';
Omar Qureshi
Just to be pedantic, innerHTML is a property, not a function.
John McCollum
I took the liberty of making that fix.
Nosredna
Thanks for pointing out / making fix
Omar Qureshi
A: 

I agree with both Noldorin and Can Berk Güder and others, and I'd like to quote that this is DOM (Document Object Model) and one of the main components of AJAX.
AJAX send a request to a server, and uses techniques such as this to "put it" in the page.

Know that you can do almost anything with javascript; you could just have "<html><body></body></html>" and have javascript do ALL the rest. This is what GWT does, and if you need to HEAVILY modify you page dynamically, you may be interested in it.

Hugo