Avatar of dancing_penguin
dancing_penguin

asked on 

DHTML and JavaScript - writing text to a <DIV> from a variable

is it possible to write text to a div with JavaScript?  i want to change adjust a number in the text based on the user input.  
Web Languages and Standards

Avatar of undefined
Last Comment
dorward
Avatar of dorward
dorward

Avatar of dorward
dorward

<div id='foo'>0
</div>
<button onclick="document.getElementById('foo').replaceChild(document.createTextNode(i++),document.getElementById('foo').firstChild)">Hello</button>
<script type="text/javascript">
var i = 1;
</script>
ASKER CERTIFIED SOLUTION
Avatar of dorward
dorward

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of dorward
dorward

Or this.

<div id='foo'>0</div>
<input  onkeyup="document.getElementById('foo').replaceChild(document.createTextNode(this.value),document.getElementById('foo').firstChild)">
Avatar of YZlat
YZlat
Flag of United States of America image

use innerHTML
Avatar of YZlat
YZlat
Flag of United States of America image

<script language="javascript">
<!--
function writeText(text){
   if (document.all)
       document.all.mydiv.innerHTML = text;
}
//-->
</script>

<div id="mydiv">
test
</div>
Avatar of dorward
dorward

innerHTML is non-standard, and document.all is positively harmful.

Use document.getElementId where possible (as it is the public standard). If you need support for Internet Explorer 4.0 (which is the only browser to support document.all but not document.getElementById) then you can do something like

if (document.getElementById) {
  obj = document.getElementById('foo');
} else if (document.all) {
  obj = document.all.foo;
}

However, given the market share of IE 4.0, it really isn't worth it.
Web Languages and Standards
Web Languages and Standards

Web development can range from developing the simplest static single page of plain text to the most complex web-based internet applications, electronic businesses, and social network services using a wide variety of languages and standards, including the familiar HTML, JavaScript and jQuery, ASP and ASP.NET, PHP, ColdFusion, CSS, PHP, Flex and Flash, but also the implementation of a broad list of standards including XML, WSDL, SSDL, VoiceXML and many more.

40K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo