将document.write与getElementById和innerHTML一起使用

时间:2014-05-23 15:29:54

标签: javascript html dom

我已经玩了一段时间,但无法让它发挥作用。任何人都知道如何从像DIV这样的元素中获取文本并在文档写入中使用它。

不确定为什么这不起作用。

<!DOCTYPE html>
<html>
<head>
<script>
document.write("<sc"+"ript>"+document.getElementById('hi').innerHTML+"</scr"+"ipt>");
</script>
</head>
<body>
<div id="hi" style="color:white">alert('test');</div>
</body>
</html> 

2 个答案:

答案 0 :(得分:1)

javascript需要在html之后。当脚本运行时,<div id="hi>"还不存在。

例如:

<!DOCTYPE html>
<html>
<body>
    <div id="hi" style="color:white">alert('test');</div>
    <script>
        document.write("<sc"+"ript>"+document.getElementById('hi').innerHTML+"</scr"+"ipt>");
    </script>
</body>
</html> 

答案 1 :(得分:0)

此脚本将在浏览器加载以下内容之前立即运行。尝试将脚本移动到页面底部,或者将其放在body的onload事件处理程序中。

<!DOCTYPE html>
<html>
    <head>
    </head>

    <body>
        <div id="hi" style="color:white">alert('test');</div>
        <script>
            document.write("<sc"+"ript>"+document.getElementById('hi').innerHTML+" </scr"+"ipt>");
        </script>
    </body>
</html> 
相关问题