创建一个新的<div>并将其插入到id为"org_div1"的element之前:
<html>
<head>
<title>||Working with elements||</title>
</head>
<script type="text/javascript">
var my_div = null;
var newDiv = null;
function addElement()
{
// create a new div element
// and give it some content
newDiv = document.createElement("div");
newDiv.innerHTML = "<h1>Hi there and greetings!</h1>";
// add the newly created element and it's content into the DOM
my_div = document.getElementById("org_div1");
document.body.insertBefore(newDiv, my_div);
}
</script>
<body onload="addElement()">
<div id='org_div1'> The text above has been created dynamically.</div>
</body>
</html>
如果有带默认值的已知属性,将会自动创建表示它们的 attribute 结点并附加到该元素上。
To create an element with a qualified name and namespace URI, use the createElementNS method.
Gecko 对 createElement 的实现并不完全遵守 DOM spec for XUL and XHTML documents:创建元素时没有设 localName 和 namespaceURI 为 null。详情见
bug 280692
。
Page last modified 06:10, 2 Dec 2007 by TigerSoldier?