Assign div text to variable then show it

后端 未结 3 1013
一整个雨季
一整个雨季 2021-01-27 08:39

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;



        
相关标签:
3条回答
  • 2021-01-27 09:04

    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 讨论(0)
  • 2021-01-27 09:13

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

    0 讨论(0)
  • 2021-01-27 09:24

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

    <script>
        var show = document.getElementById("box").innerHTML;
        document.write(show);
    </script>
    
    0 讨论(0)
提交回复
热议问题