Jake
Jake

Reputation: 1057

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.

Upvotes: 0

Views: 20896

Answers (3)

Timidfriendly
Timidfriendly

Reputation: 3284

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

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

Upvotes: 3

Gindi Bar Yahav
Gindi Bar Yahav

Reputation: 65

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

Upvotes: 0

VisioN
VisioN

Reputation: 145408

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

Upvotes: 1

Related Questions