Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
85
rated 0 times [  87] [ 2]  / answers: 1 / hits: 43955  / 11 Years ago, sun, january 12, 2014, 12:00:00

I have a JavaScript function that uses document.write() to write to the page. My issue is that when I click the button to call the function, document.write() 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:



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

<script>
<!-- JavaScript to load Google Maps -->
</script>
</head>

<body>
<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>
</div>
</div>

</body>




...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();

document.write(<h1> + myyear + / + mymonth + /+mytoday + /h1>);
}


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



Thanks,
Josh


More From » html

 Answers
18

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 ! -->
</div>


Then



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


[#73223] Friday, January 10, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lincolnx

Total Points: 602
Total Questions: 90
Total Answers: 94

Location: Saint Lucia
Member since Wed, Feb 8, 2023
1 Year ago
;