15

How to dynamically change content of a div using JavaScript?

Charles Sprayberry
  • 7,741
  • 3
  • 41
  • 50
Rikard
  • 167
  • 1
  • 1
  • 3

4 Answers4

26

This should do it:

<div id="foo">Div you want to change</div>

And in JavaScript:

document.getElementById('foo').innerHTML = 'Your content';
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185
  • so does it mean you are going to write a simple js file which is going to run when for instance, a button is clicked? and can you also tell me how that can be done (I am sorry, I'm very new to javascript coz it sounds a little dumb to me, being a programmer) – Chibueze Opata Mar 01 '11 at 14:58
8

document.getElementById("divId").innerHTML = "new content!"

I would recommend using a framework like jQuery though, because chances are you will be doing more things like this later.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Carlos Blanco
  • 8,592
  • 17
  • 71
  • 101
  • 4
    +1 and a sidenote, if you don't want to affect the actual HTML inside and just want to change the text inside use .innerText instead. – Joel Etherton Feb 03 '10 at 01:47
3

Its worth noting that you can also use innerHTML to include other markup. Also if the DIV des not have an ID you can try using getElementsByTagName.

Example, to get the first DIV in the document:

document.getElementsByTagName("div")[0].innerHTML = "<p>This is a <span>new</span> paragraph</p>";

This allows you to loop through multiple DIVs in the document and check other conditions.

And like they said above, if the DIV has an ID that you know will always be there, then thats better to use:

document.getElementById("theID").innerHTML = "<p>This is a <span>new</span> paragraph</p>";

Check out Prototype (links below) (or jQuery) in handling this as they make life easier, especially when you get into CSS selectors:

donohoe
  • 13,867
  • 4
  • 37
  • 59
-2
$(document).ready(function(){

$('#btn').click(function(){   

    $('#div_content').load('html.page');

 });
});
Nazik
  • 8,696
  • 27
  • 77
  • 123
varun
  • 1