Assign div text to variable then show it

I have a simple task I'm trying to accomplish learning JavaScript but haven't been able to find a clear answer. Here's the code;

<script type="text/javascript">
var show = document.getElementById("box");
document.write(show);
</script>


<div id="box">Testing</div>

Basically I want the text in the box div to be stored into a variable. Then, I want to display that variable's text on a different part of the page. With the code above I get a null error.

Thanks.

Asked By: Jake
||

Answer #1:

http://jsfiddle.net/David_Knowles/LTfyH/

<script>
    var show = document.getElementById("box").innerHTML;
    document.write(show);
</script>
Answered By: Timidfriendly

Answer #2:

First of all, your JavaScript should find the element you address. Hence you need to put your <script> tag after the element is defined (this is one easy way).

Next, using .getElementById() you can find element, but to get inner HTML out of it, you need to target .innerHTML property:

<div id="box">Testing</div>

<script type="text/javascript">
    var element = document.getElementById("box"),
        value = element.innerHTML;

    console.log(value);
</script>

Finally, for testing purposes you'd better use console. To make your script output values to the console, use console.log().

Answered By: VisioN

Answer #3:

What you're doing is storing the DOM Object in the variable, not the text. You should access the innerHTML property to access the text.

var t = document.getElementById("foo").innerHTML;
t = t.trim(); // to remove the whitespaces before and after the div.
document.write(t); 
Answered By: Gindi Bar Yahav
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles