user3015565 user3015565 - 1 year ago 62
Javascript Question

Write text inside a div from JavaScript?

I have a JavaScript function that uses

to write to the page. My issue is that when I click the button to call the function,
replaces what I already had with what I am writing. Is there a way to write text to a specific div from JavaScript?

Here is my HTML code:

<link href="style.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="javascript.js">
// Calling the Google Maps API

<!-- JavaScript to load Google Maps -->

<div class="content">
<div id="googleMap"></div>
<div id="right_pane_results">hi</div>this -->
<div id="bottom_pane_options">
<button onclick="todaydate()">Try It</button>


...and my JavaScript code (something I got from the internet just to test):

function todaydate() {
var today_date=new Date()
var myyear=today_date.getYear()
var mymonth=today_date.getMonth() + 1
var mytoday=today_date.getDate()

I would like the text to be right below the button. Any help would be appreciated.


Answer Source

You should avoid document.write. You'd better put your results to another div:

 <div id="bottom_pane_options">
     <button onclick="todaydate();">Try It</button>
     <div id="results"></div>   <!-- Added div ! -->


function todaydate() {
    var today_date=new Date();
    var myyear=today_date.getYear();
    var mymonth=today_date.getMonth() + 1;
    var mytoday=today_date.getDate();

    document.getElementById('results').innerHTML ="<h1>" + myyear + "/" + mymonth + "/" + mytoday + "</h1>";

As you can see, we're writing the results to the results div with .innerHTML.

Hope this helps. Cheers