最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Assign div text to variable then show it - Stack Overflow

programmeradmin1浏览0评论

I have a simple task I'm trying to acplish 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.

I have a simple task I'm trying to acplish 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.

Share Improve this question asked May 15, 2013 at 21:26 JakeJake 1,0573 gold badges11 silver badges13 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 3

http://jsfiddle/David_Knowles/LTfyH/

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

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

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); 
发布评论

评论列表(0)

  1. 暂无评论