我正在尝试一个简单的练习,其中我想将一个由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>
谢谢!
答案 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);