I am new to Javascript (and programming in general) and have been trying to get a basic grasp on working with the DOM. Apologies if this is a very basic mistake, but I looked around and couldn’t find an answer.
I am trying to use the appendChild method to add a heading and some paragraph text into the in the very basic HTML file below.
<html>
<head>
<title>JS Practice</title>
</head>
<body>
<script src="script.js"></script>
<div id = "main">
<h1>Simple HTML Page</h1>
<p>This is a very simple HTML page.</p>
<p>It's about as basic as they come. It has: </p>
<ul>
<li>An H1 Tag</li>
<li>Two paragraphs</li>
<li>An unordered list</li>
</ul>
</div>
<div id="javascript">
</div>
</body>
</html>
Here is the js code:
var newHeading = document.createElement("h1");
var newParagraph = document.createElement("p");
newHeading.innerHTML = "New Heading!";
newParagraph.innerHTML = "Some text for a paragraph.";
document.getElementById("javascript").appendChild(newHeading);
document.getElementById("javascript").appendChild(newParagraph);
Running it causes an error: «Cannot call method ‘appendChild’ of null»
Help? I can’t figure out why this isn’t working…
asked Dec 29, 2011 at 16:35
Assuming this code is inside the script.js
file, this is because the javascript is running before the rest of the HTML page has loaded.
When an HTML page loads, when it comes across a linked resource such as a javascript file, it loads that resource, executes all code it can, and then continues running the page. So your code is running before the <div>
is loaded on the page.
Move your <script>
tag to the bottom of the page and you should no longer have the error. Alternatively, introduce an event such as <body onload="doSomething();">
and then make a doSomething()
method in your javascript file which will run those statements.
answered Dec 29, 2011 at 16:38
TejsTejs
40.5k10 gold badges67 silver badges85 bronze badges
0
There is an easier way to resolve this issue. Put your JavaScript inside of a function and use the window.onload. So for instance:
window.onload = function any_function_name()
{
var newHeading = document.createElement("h1");
var newParagraph = document.createElement("p");
newHeading.innerHTML = "New Heading!";
newParagraph.innerHTML = "Some text for a paragraph.";
document.getElementById("javascript").appendChild(newHeading);
document.getElementById("javascript").appendChild(newParagraph);
}
Now, you do not have to move your tag because that will run your code after the HTML has loaded.
answered Feb 27, 2014 at 21:40
BrendanBrendan
1,35912 silver badges17 bronze badges
Your script is running before the elements are available.
Place your script directly before the closing </body>
tag.
<html>
<head>
<title>JS Practice</title>
</head>
<body>
<div id = "main">
<h1>Simple HTML Page</h1>
<p>This is a very simple HTML page.</p>
<p>It's about as basic as they come. It has: </p>
<ul>
<li>An H1 Tag</li>
<li>Two paragraphs</li>
<li>An unordered list</li>
</ul>
</div>
<div id="javascript">
</div>
<!-- Now it will run after the above elements have been created -->
<script src="script.js"></script>
</body>
</html>
0
Your DOM is not loaded, so getElementById will return null, use document.ready() in jquery
$(document).ready(function(){
var newHeading = document.createElement("h1");
var newParagraph = document.createElement("p");
newHeading.innerHTML = "New Heading!";
newParagraph.innerHTML = "Some text for a paragraph.";
document.getElementById("javascript").appendChild(newHeading);
document.getElementById("javascript").appendChild(newParagraph);
}
answered May 9, 2017 at 9:10
Ignatius AndrewIgnatius Andrew
7,8223 gold badges53 silver badges54 bronze badges
I add an event listener to wait for DOM content to fully load
document.addEventListener("DOMContentLoaded", function() {
place_the_code_you_want_to_run_after_page_load
})
Dmitry
1,9861 gold badge17 silver badges21 bronze badges
answered Sep 16, 2016 at 3:19
Because your JavaScript file is loaded first, and that time when you write window.document.body.appendChild(btn)
, body
element is not loaded in html, that’s why you are getting error here, you can load the js file once body element is loaded in DOM.
index.html
<html>
<head>
<script src="JavaScript.js"></script>
</head>
<body onload="init()">
<h3> button will come here</h3>
</body>
</html>
JavaScript.js
function init(){
var button = window.document.createElement("button");
var textNode = window.document.createTextNode("click me");
button.appendChild(textNode);
window.document.body.appendChild(button);
}
Yangshun Tay
46.6k31 gold badges116 silver badges138 bronze badges
answered Jun 6, 2017 at 6:45
sunny raisunny rai
5155 silver badges6 bronze badges
- Table of contents
- AppendChild() is not a function javascript
- .appendChild is not a function [duplicate]
- Solve — appendChild is not a function Error in JavaScript
- AppendChild() is not a function [duplicate]
- .appendChild() is not a function when using jQuery
- JavaScript Error = appendChild is not a function [fechada]
- JavaScript appendChild
AppendChild() is not a function javascript
<head runat="server"> <script type="text/javascript" language="javascript"> function createQuestionPanel() { var element = document.createElement("Input"); element.setAttribute("type", "button"); element.setAttribute("value", "button"); element.setAttribute("name", "button"); var div = '<div>top div</div>'; div[0].appendChild(element); } function formvalidate() { } </script> </head> <body onload="createQuestionPanel()"> </body> </html>
var div = '<div>top div</div>';
var div = document.createElement('div'); div.appendChild(document.createTextNode('top div')); div.appendChild(element);
function createQuestionPanel() { var element = document.createElement("Input"); element.setAttribute("type", "button"); element.setAttribute("value", "button"); element.setAttribute("name", "button"); var div = document.createElement("div"); <------- Create DIv Node div.appendChild(element);<-------------------- document.body.appendChild(div) <------------- Then append it to body } function formvalidate() { }
var div = '<div>top div</div>';
<div id="div1"> <p id="p1">This is a paragraph.</p> <p id="p2">This is another paragraph.</p> </div> <script> var para = document.createElement("p"); var node = document.createTextNode("This is new."); para.appendChild(node); var element = document.getElementById("div1"); element.appendChild(para); </script>
var div = '<div>top div</div>'; // you just created a text string
var div = document.createElement("div"); // we want a DIV element instead div.innerHTML = "top div";
var div = document.createElement("div"); div.innerHTML = "topdiv"; div.appendChild(element); document.body.appendChild(div);
.appendChild is not a function [duplicate]
var para = document.createElement("tr"); var node = document.createTextNode(data.filename); para.appendChild(node); var el = document.getElementsByClassName("toBeSelected"); el.appendChild(para);
document.getElementsByClassName ^
var el = document.getElementsByClassName("toBeSelected")[0];
elems = document.getElementsByClassName('toBeSelected'); for (i = 0; i < elems.length; i++) { elem = elems[i]; tr = document.createElement('tr'); tr.textContent = data.filename; elem.appendChild(tr); }
$('<tr>').text(data.filename).appendTo('.toBeSelected');
Solve — appendChild is not a function Error in JavaScript
Copied!<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <!-- ✅ Your JS script here ✅ --> <script src="index.js"></script> </body> </html>
Copied!const boxes = document.getElementsByClassName('box'); console.log(boxes); // 👉️ [div.box, div.box, div.box] const child = document.createElement('div'); child.innerHTML = `<h1>Hello world</h1>`; // ⛔️ TypeError: appendChild is not a function boxes.appendChild(child);
Copied!const boxes = document.getElementsByClassName('box'); console.log(boxes); // 👉️ [div.box, div.box, div.box] const child = document.createElement('div'); child.innerHTML = `<h1>Hello world</h1>`; // ✅ Works boxes[0].appendChild(child);
Copied!const box = null; if (typeof box === 'object' && box !== null && 'appendChild' in box) { const child = document.createElement('div'); child.innerHTML = `<h1>Hello world</h1>`; box.appendChild(child); }
AppendChild() is not a function [duplicate]
var body = $('body'); var container = document.getElementsByTagName("container"); var tileTab = new Array(); var windowWidth = window.innerWidth; var windowHeight = window.innerHeight; var nbTileWidth = Math.floor(windowWidth / 50) - 1; var nbTileHeight = Math.floor(windowHeight / 50) - 1; var x = 0; for(var i = 0; i < nbTileHeight; i++){ var row = document.createElement("div"); for(var j = 0; j < nbTileWidth; j++){ tileTab[x] = document.createElement("div"); row.appendChild(tileTab[x]); tileTab[x].className = "tile"; x++; } container.appendChild(row); row.className = "row"; } body.appendChild(container);
container.appendChild is not a function
var body = $('body'); var container = document.getElementsByTagName("container");
var body = document.body; var container = document.querySelector('.container');
.appendChild() is not a function when using jQuery
recipeDiv = []; recipeDiv[i] = document.createElement("div"); recipeDiv[i].setAttribute("class", "recipeBlock"); recipeDiv[i].appendChild(someElement);
recipeDiv = []; recipeDiv[i] = $("<div/>").addClass("recipeBlock"); recipeDiv[i].appendChild(someElement);
var recipeContainer = $("<div/>") .addClass("recipeContainer") .appendTo("body"); var recipeDiv = []; var likes = []; for (var i = 0; i < 20; i++) { //Create divs so you get a div for each recipe recipeDiv[i] = $("<div/>").addClass("recipeBlock"); //Create divs to contain number of likes likes[i] = $("<div/>") .addClass("likes") .html("<b>Likes</b>"); //Append likes blocks to recipe blocks recipeDiv[i].append(likes[i]); //Append recipe blocks to container recipeContainer.append(recipeDiv[i]); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
recipeDiv = []; var someElement = $("<div/>").addClass("recipeBlock"); recipeDiv[i].appendChild(someElement);
JavaScript Error = appendChild is not a function [fechada]
function inserirNumeros(x) { let paragraph = document.createElement("p"); let node = document.createTextNode("this is new"); paragraph.appendChild(node); let display = document.getElementsByClassName("display"); display.appendChild(paragraph) }
<body> <h1>Calculadora</h1> <div class="corpo"> <div class="display">0</div> <div class="numeros"> <div class="botoes" id="7" onclick="inserirNumeros(7)" value="7">7</div> <div class="botoes" id="8">8</div> <div class="botoes" id="9">9</div> <div class="operacoes" id="divisao">÷</div> </div> </div> </body>
function inserirNumeros(x) { let paragraph = document.createElement("p"); let node = document.createTextNode("this is new"); paragraph.appendChild(node); let display = document.getElementsByClassName("display")[0]; display.appendChild(paragraph) }
<body> <h1>Calculadora</h1> <div class="corpo"> <div class="display">0</div> <div class="numeros"> <div class="botoes" id="7" onclick="inserirNumeros(7)" value="7">7</div> <div class="botoes" id="8">8</div> <div class="botoes" id="9">9</div> <div class="operacoes" id="divisao">÷</div> </div> </div> </body>
function inserirNumeros(x) { let paragraph = document.createElement("p"); let node = document.createTextNode("this is new"); paragraph.appendChild(node); let display = document.getElementById("display"); display.appendChild(paragraph) }
<body> <h1>Calculadora</h1> <div class="corpo"> <div id="display">0</div> <div class="numeros"> <div class="botoes" id="7" onclick="inserirNumeros(7)" value="7">7</div> <div class="botoes" id="8">8</div> <div class="botoes" id="9">9</div> <div class="operacoes" id="divisao">÷</div> </div> </div> </body>
function inserirNumeros(x) { let paragraph = document.createElement("p"); let node = document.createTextNode("this is new"); paragraph.appendChild(node); let display = document.querySelector(".display"); display.appendChild(paragraph) }
<body> <h1>Calculadora</h1> <div class="corpo"> <div class="display">0</div> <div class="numeros"> <div class="botoes" id="7" onclick="inserirNumeros(7)" value="7">7</div> <div class="botoes" id="8">8</div> <div class="botoes" id="9">9</div> <div class="operacoes" id="divisao">÷</div> </div> </div> </body>
JavaScript appendChild
.wp-block-code { border: 0; padding: 0; } .wp-block-code > div { overflow: auto; } .shcb-language { border: 0; clip: rect(1px, 1px, 1px, 1px); -webkit-clip-path: inset(50%); clip-path: inset(50%); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; word-wrap: normal; word-break: normal; } .hljs { box-sizing: border-box; } .hljs.shcb-code-table { display: table; width: 100%; } .hljs.shcb-code-table > .shcb-loc { color: inherit; display: table-row; width: 100%; } .hljs.shcb-code-table .shcb-loc > span { display: table-cell; } .wp-block-code code.hljs:not(.shcb-wrap-lines) { white-space: pre; } .wp-block-code code.hljs.shcb-wrap-lines { white-space: pre-wrap; } .hljs.shcb-line-numbers { border-spacing: 0; counter-reset: line; } .hljs.shcb-line-numbers > .shcb-loc { counter-increment: line; } .hljs.shcb-line-numbers .shcb-loc > span { padding-left: 0.75em; } .hljs.shcb-line-numbers .shcb-loc::before { border-right: 1px solid #ddd; content: counter(line); display: table-cell; padding: 0 0.75em; text-align: right; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; white-space: nowrap; width: 1%; }parentNode.appendChild(childNode);Code language: CSS (css)
<ul id="menu"> </ul>Code language: HTML, XML (xml)
function createMenuItem(name) { let li = document.createElement('li'); li.textContent = name; return li; } // get the ul#menu const menu = document.querySelector('#menu'); // add menu item menu.appendChild(createMenuItem('Home')); menu.appendChild(createMenuItem('Services')); menu.appendChild(createMenuItem('About Us')); Code language: JavaScript (javascript)
<ul id="menu"> <li>Home</li> <li>Services</li> <li>About Us</li> </ul>Code language: HTML, XML (xml)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>JavaScript appendChild() Demo</title> </head> <body> <ul id="menu"> </ul> <script> function createMenuItem(name) { let li = document.createElement('li'); li.textContent = name; return li; } // get the ul#menu const menu = document.querySelector('#menu'); // add menu item menu.appendChild(createMenuItem('Home')); menu.appendChild(createMenuItem('Services')); menu.appendChild(createMenuItem('About Us')); </script> </body> </html> Code language: HTML, XML (xml)
<ul id="first-list"> <li>Everest</li> <li>Fuji</li> <li>Kilimanjaro</li> </ul> <ul id="second-list"> <li>Karakoram Range</li> <li>Denali</li> <li>Mont Blanc</li> </ul> Code language: HTML, XML (xml)
// get the first list const firstList = document.querySelector('#first-list'); // take the first child element const everest = firstList.firstElementChild; // get the second list const secondList = document.querySelector('#second-list'); // append the everest to the second list secondList.appendChild(everest) Code language: JavaScript (javascript)
Next Lesson PHP Tutorial
08.09.2015, 18:50 |
|||
|
|||
Не работает .appendChild(); Доброго времени суток. в браузерах Google Chrome и Ie9 не работает .appendChild(); Проверяю на ошибки на jsfiddle и всё работает вот ссылка на пример https://jsfiddle.net/vqc2fahz/1/ Но на сервере не хочет работать… в консоли следующие сообщение об ошибке: Uncaught ReferenceError: obj is not defined Вот код файла <html> <head> <title>Js-practic</title> <link rel="stylesheet" type="text/css" href="css/style.css"> <script type="text/javascript"> var ul = document.createElement('ul'); ul.innerHTML = '<li>Hello, world!</li>'; obj.appendChild(ul); </script> </head> <body> <div id="obj"></div> </body> </html> Как можно исправить эту ошибку, чтобы на сервере заработало? |
08.09.2015, 18:54 |
|||
|
|||
Так же пробовал такой вариант var ul = document.createElement('ul'); ul.innerHTML = '<li>Hello, world!</li>'; var ob = document.getElementById('obj'); ob.appendChild(ul); Также не работает на сервере, только меняется лог ошибки: Cannot read property ‘appendChild’ of null |
08.09.2015, 19:21 |
|||
|
|||
Вопрос закрыт… Ошибка новичка — необходимо объявить скрипту чтобы он загружался только после загрузки всех DOM элементов. для этого я использовал jquery $( document ).ready(function() { var ob = document.getElementById(‘obj’); |
08.09.2015, 19:32 |
|||
|
|||
А не жирно ли ради этого JQ использовать? |