admin管理员组

文章数量:1389758

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!

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!

Share Improve this question edited Jun 7, 2009 at 16:07 asked Jun 7, 2009 at 16:03 AdamAdam
Add a ment  | 

5 Answers 5

Reset to default 6

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

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>');

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.

You are probably looking for the innerHTML property

document.getElementById('topics').innerHTML = 'whatever';

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

本文标签: Using Javascript to add HTMLStack Overflow