如何使用JavaScript创建新标签?

时间:2014-03-06 23:41:50

标签: javascript

我是JavaScript的新手 任何人都可以告诉我为什么我的代码显示不起作用?

<!DOCTYPE html>
<!-- links.html by Bill Weinman http://bw.org/contact/ -->

<html lang='en'>
<head>
    <meta charset="UTF-8" /> 
    <title>
        HTML Hyperlinks
    </title>        
</head>
<body>


<div id = "123">
<p id = "main">
    Here is a link to <a name = "hyper" href="http://yahoo.com/">page</a>.
    The text around the link is not part of the link. 
</p>
<script>


        var newTag = document.createElement("ul");
        var existingElement = document.getElementsByTagName("div");
        existingElemen[0].appendChild ( newTag );
        var newLiTag =  document.createElement("li");
        newTag.appendChild (newLiTag);
        var textNode = document.createTextNode("here is the first unOrderedList");
        newLiTag.appendChild (textNode);

</script>

</div>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

您的代码中存在拼写错误:

existingElemen[0].appendChild ( newTag );

应该是......

existingElement[0].appendChild( newTag );

一个小但相关的注释......如果你要构建一个大的DOM元素列表,你要添加到页面中,你可能想先用JavaScript构建一组元素(例如1 <ul>其中包含250个<li>个元素,然后 将其添加到页面中。这使浏览器触发1个布局更新,而不是251个单独的布局更新。 ; - )

答案 1 :(得分:1)

错字:

existingElemen[0].appendChild ( newTag );

应该是:

existingElement[0].appendChild( newTag );

在此处查看:http://jsfiddle.net/c3REN/