开发者

Experimenting with DOM functions

Most of the experience I have manipulating HTML elements using Javascript involves the innerHTML property. My knowledge is severely lacking when it comes to DOM manipulation. So, to try and rectify this, I've been experimenting with Javascript DOM functions.

A simple test is to merely add a node to the DOM. There are countless tutorials on the Internet which demonstrate how to do this, and yet for some reason I'm unable to get it to actually work.

In the following test code, I have an HTML input element that, when clicked, triggers a Javascript function that is supposed to simply add a div element to the DOM and make it appear on the screen.

<html>
<head>
<script type = "text/javascript">
function test()
{
    var newDiv = document.createElement("div");
    newDiv.innerHTML = "<h1>blah blah</h1>";
    document.body.insertBefore(newDiv, document.getElementById('DOMTester'));
}
</script>
</head>

<body>
<div>
<input id='DOMTester' type='submit' onclick='test()'>
</div>

</body>
</html>

However, this doesn't work. It generates an e开发者_如何学运维xception on Firefox when insertBefore() is called: "Node was not found" code: "8" nsresult: "0x80530008 (NS_ERROR_DOM_NOT_FOUND_ERR)"

Why does this fail? Shouldn't this simply insert the new div element before the submit button?


You're trying to insert the node into the <body>, but the <body> tag is not the parent of your input element. Try giving the <div> around the <input> an "id" value, and then do:

document.getElementById("theDiv").insertBefore(newDiv, document.getElementById('DOMTester'));


Simpler test:

document.body.appendChild(newDiv);

Your problem is that when you supply a reference element it must be a child of the element that is the receiver of the insertBefore method (in this case document.body). Do:

var tester = document.getElementById('DOMTester');
tester.parentNode.insertBefore(newDiv,tester);


Here you go:

var input = document.getElementById('DOMTester');

input.onclick = function() {
    var newDiv = document.createElement('div');
    newDiv.innerHTML = '<h1>blah blah</h1>';
    this.parentNode.insertBefore(newDiv, this);
};

Live demo: http://jsfiddle.net/simevidas/NwnKU/


You need to take off the extra div surrounding the input#DOMTester:

http://jsfiddle.net/Xycve/

<html>
<head>
<script type = "text/javascript">
function test()
{
    var newDiv = document.createElement("div");
    newDiv.innerHTML = "<h1>blah blah</h1>";
    document.body.insertBefore(newDiv, document.getElementById('DOMTester'));
}
</script>
</head>

<body>
<input id='DOMTester' type='submit' onclick='test()'>

</body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜