To be sure that the document is loaded, add your script in a function called when the DOMContentLoaded event is triggered.
window.addEventListener('DOMContentLoaded', (event) => {
... your code here
});
To be sure that the document is loaded, add your script in a function called when the DOMContentLoaded event is triggered.
window.addEventListener('DOMContentLoaded', (event) => {
... your code here
});
I am trying to create a li
item and append the fragment dynamically to ul
using only javascript. it is part of a project. I have written a code but every time the console is giving me a different error, the last one was “document is not defined”. I need to know what I am doing wrong.
the errors I get on the console was:
1- getAttribute is not a function.
2-document is not defined
3- appendChild is not a function.
4- cannot appendChild to null
const nav_list= document.querySelectorAll("section");
const myUl = document.getElementById("navbar__list");
// create fragment
let nav_fragment = document.createDocumentFragment();
function addItemList(){
for (let i = 0; i < nav_list.length; i++){
let newText= nav_list[i].getAttribute("data-nav");
// creat new li
let newLi= documnet.creatElement("li");
// create new link
let newLink= document.createElement ("a");
// create text node
let textNode = document.creatTextNode ("newText");
// add eventListener
newLink.addEventListener("click", function(){
section[i].scrollIntoView({behavior : "smooth"});
});
newLink.appendChild(textNode);
newLi.appendChild(newLink);
nav_fragment.appendChild(newLi);
}
myUl.appendChild(nav_fragment);
}
// Build menu
addItemList();
** edit: the script tag is added at the bottom of the html right before the .
are you adding the script to head section? if yes, try adding it before closing
, also you can use
the script is added at the bottom of the html right before the