I have a javascript function and then below it I have some html. In the html I want to be able to document.write() a variable from that function above. Is this possible?? Basically if I have function x() with some variable declared inside of it, I want to be able to document.write() it somewhere else in my html. Thanks in advance.

Hi,

There are many methods to write on HTML through javacript. You can also have a look on 'innerHTML' propertyof javascipt.

I have a javascript function and then below it I have some html. In the html I want to be able to document.write() a variable from that function above. Is this possible?? Basically if I have function x() with some variable declared inside of it, I want to be able to document.write() it somewhere else in my html. Thanks in advance.

You will need to use the DOM to write to a specific Element. The HTML elements are viewed as DOM nodes. DOM Nodes have a set of function that allow you to manipulate that node, access its properties, or reference other nodes from it.

The first thing you'll need is to reference the DOM node (HTML Element) that you want to "write" to. Write, in this case would mean manipulating the Text node of that HTML Element.

Let say you have the HTML below in an html document:

<div id="target"></div>

To reference that DOM node you can use the getElementById() method of a parent Node. Usually the document node is used.

var div = document.getElementById('target');

To change its text node, you could use the innerHTML property (which isn't a DOM specification but it works).

eg:

// reference the DOM node you want to manipulate
var div = document.getElementById('target');
// user the non-standard innerHTML property to change the HTML in that node
div.innerHTML = 'hello world';

To use true DOM methods you would do something like:

// get ref
var div = document.getElementById('target');
// create a text Node
var txt = document.createTextNode('Hello DOM');
// append your text node to the node you want the text to display in
div.appendChild(txt);

Here is a link to help you out:
http://www.howtocreate.co.uk/tutorials/javascript/dombasics

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.