JS中的createTextNode无法在Chrome中运行

时间:2013-05-14 17:42:15

标签: javascript console createtextnode

我正在尝试一个简单的练习,其中我想将一个由JavaScript生成的

附加到id为“target-area”的div。 问题是Chrome拒绝注入此段并给我一个错误: 未捕获的TypeError:Object#没有方法'createTextNode'

以下是代码:

<html>
<head>
    <title>JS</title>

</head>
<body>
    <div id="target-area">
        <p id="tagline">Hello World!</p>
    </div>

</body>
<script type="text/javascript">

        // store the target area to a variable to keep things neat
        var targetArea = document.getElementById("target-area");
        // create our <p> element
        var p = document.createElement("p");
        // create a text node inside the <p>, note that we're using a variable "p" here
        var snippet = p.createTextNode("this was a generated paragraph");
        // insert our generated paragraph into the DOM
        targetArea.appendChild(snippet);

    </script>
</html>

谢谢!

2 个答案:

答案 0 :(得分:2)

文档具有createTextNode 属性,而不是刚刚创建的元素

所以基本上你的代码应该是这样的..

    // store the target area to a variable to keep things neat
    var targetArea = document.getElementById("target-area");
    // create our <p> element
    var p = document.createElement("p");
    // create a text node inside the <p>, note that we're 
    //  using a variable "p" here
   var snippet = document.createTextNode("this was a generated paragraph");
    // insert our generated paragraph into the DOM
    p.appendChild(snippet);
    targetArea.appendChild(p);

<强> Check Fiddle

答案 1 :(得分:0)

只是出于好奇。

为什么不简单?

// store the target area to a variable to keep things neat
var targetArea = document.getElementById("target-area");
// create our <p> element
var p = document.createElement("p");
// create a text node inside the <p>, note that we're 
//  using a variable "p" here
var snippet = document.createTextNode("this was a generated paragraph");
// insert our generated paragraph into the DOM
targetArea.appendChild(snippet);