Channel72
Channel72

Reputation: 24729

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 exception 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?

Upvotes: 1

Views: 462

Answers (4)

William Niu
William Niu

Reputation: 15853

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>

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185963

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/

Upvotes: 1

Phrogz
Phrogz

Reputation: 303371

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);

Upvotes: 2

Pointy
Pointy

Reputation: 413826

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'));

Upvotes: 3

Related Questions