Reputation: 1097
Using this code
var html='<div class="somediv"></div>';
var target=document.getElementById('contentArea');
target.appendChild(html);
I'm getting
Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
Uncaught TypeError: Cannot call method 'appendChild' of null
Any suggestion?
Upvotes: 1
Views: 2704
Reputation: 544
I got the same error Uncaught Error: NOT_FOUND_ERR: DOM Exception 8
trying to prepend an array of jQuery objects to a DOM Element. I found out that the spec allows you to prepend an array of DOM elements but not an array of jQuery objects.
Read this: http://bugs.jquery.com/ticket/11231 for details
Upvotes: 0
Reputation: 119867
In doing DOM operations, before you get a hold of an element, make sure those elements are loaded already. putting the script to the bottom, just before the </body>
tag should do
//all other HTML up here
<script>
var html=document.createElement('div');
html.className = 'somediv';
var target=document.getElementById('contentArea');
target.appendChild(html);
</script>
</body>
or you can run scripts using window.onload
The
load
event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
window.onload = function() {
var html=document.createElement('div');
html.className = 'somediv';
var target=document.getElementById('contentArea');
target.appendChild(html);
}
Upvotes: 2
Reputation:
Can't say for sure since you didn't provide the DOM from which you're selecting, but I'd guess that you're running your script before the contentArea
element exists.
If so, place your script at the end of the body
element.
<head>
...
</head>
<body>
<div id="contentArea">
...
</div>
<script type="text/javascript">
// your script here
</script>
</body>
Alternatively, just wrap everything inside:
window.onload = function(){
// your script here
}
Not directly related, but you shouldn't be passing an HTML string to appendChild
. You should create a DOM node, and append that.
var target=document.getElementById('contentArea');
target.appendChild(document.createElement('div')).className = 'somediv';
Upvotes: 3
Reputation: 4524
var target=document.getElementById('contentArea');
was not able to find the element with ID contentArea
. Can you post the rest of the code?
Upvotes: 1