creating a dynamic ul using Javascript - javascript

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 .

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

Related

Replace text with an anchor tag which can call a function on click

I have an XML string which is displayed in a span in a pre tag:
<pre className="xmlContainer">
<span id="xml-span"></span>
</pre>
The XML looks something like this:
<root>
<child-to-replace>
<child-to-replace/>
...
<root/>
With multiple (unknown) number of the child-to-replace tag.
I replace < and > to display the xml which is contained in a variable xml:
let element = document.getElementById('xml-span');
var displayXml = xml.replaceAll('<','<').replaceAll('>','>');
element.innerHTML = displayXml;
I also want to replace all instances of the opening tag of child-to-replace with an anchor tag which calls a function updateParentScope. I have tried to simply replace it:
function updateParentScope(scope) {
//updates scope for parent
}
useEffect(() => {
let element = document.getElementById('xml-new');
var displayXml = xml.replaceAll('<','<').replaceAll('>','>')
.replaceAll('child-to-replace',
'<a onclick="updateParentScope(\"sometext\")" >child-to-replace</a>')
element.innerHTML = displayXml;)
element.innerHTML = replaced;
}, [xml])
This gives Uncaught ReferenceError: updateParentScope is not defined when clicked.
Is there a way to solve this or is replacing the text the wrong approach?
The solution I found was to change the anchor tag to a button, then get the element from the DOM after render with a useEffect hook. When the element is retrieved, add an event listener.
useEffect(() => {
const cond = document.getElementById(btnId) || false;
if (cond && !hasEventListener){
var btn = document.getElementById(btnId);
btn.addEventListener('click', updateParentScope)
setHasEventListener(true);
}
setHasEventListener(false);
})
The cond check is to make sure the element is rendered in the DOM.
I needed to add hasEventListener to state in order to not add the event listener multiple times:
const [hasEventListener, setHasEventListener] = useState(false);
This is not an ideal solution as the function called by the click event does not accept parameters.

Insert Div into the DOM and add attributes in Angular using Javascript

Would there be any reason the following code would not insert a DIV into the DOM and add the ID attribute? For some reason it is not working:
createDivs() {
const target = document.querySelector(".navbar");
const createDiv = document.createElement("DIV");
createDiv.setAttribute("id", "result-div");
createDiv.innerHTML = "<p>Yes</p>";
createDiv.insertAdjacentElement("afterbegin", target);
}
ngOnInit() {
this.createDivs();
}
You called insertAdjacentElement on the new element instead of on the sibling element... check the documentation
Instead of using
createDiv.insertAdjacentElement("afterbegin", target);
you should use
target.insertAdjacentElement("afterbegin", createDiv);

How can i make my new bullet points display a string?

First time posting, sorry if i do something wrong.
When i try to make a new list with js, the list elements only display [object HTMLLIElement] in the DOM. I would want it to make a new bullet point which says "Hello" each time i press the button.
It only shows this https://gyazo.com/f441c11ce81d80ff14ba4e207c1a7e2d
Here's my code.
var bodyEl = document.querySelector("body");
var ulist = document.createElement("ul");
var bulletpointEl = document.createElement("li");
bulletpointEl.innerHTML = "hello"
bodyEl.appendChild(ulist);
function bulletpoint() {
ulist.innerHTML += bulletpointEl;
}
<button onclick="bulletpoint()">New bulletpoint</button>
You have to use appendChild instead of innerHTML. To create new li element in each button click, you have to create that inside the function.
I will also suggest you to use textContent instead of innerHTML when the content is simple text.
var bodyEl = document.querySelector("body");
var ulist = document.createElement("ul");
function bulletpoint(){
var bulletpointEl = document.createElement("li");
bulletpointEl.textContent = "hello"
ulist.appendChild(bulletpointEl);
bodyEl.appendChild(ulist);
}
<button onclick="bulletpoint()">New bulletpoint</button>
back
The problem is that you're trying to give innerHTML an object instead of a string.
innerHTML accepts a string - https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Syntax
If you want to append an html element to the ulist you'll need to use the .appendChild() method same as you did with the bodyEl -
function bulletpoint(){
ulist.appendChild(bulletpointEl);
}
Hope this helps!

Formatting a href link with appendChild, setAttribute, etc

I am attempting to populate a list with href links via javascript.
Here is an example of the html I would like to create:
<li> Complete blood count</li>
Where "#modal-one" displays a pop up.
I have used the following and several other iterations to try and create this dynamically:
<script>
var listItem = [];
function createTestList() {
var tests = results.tests; //an array to tests to populate list
var i;
var j;
for (i = 0; i < tests.length ; i++ ){
listItem[i] = document.createElement("li");
var node = document.createTextNode(tests[i].name);
listItem[i].appendChild(node);
listItem[i].setAttribute("href", "#modal-one");
addOnClick(i);
//var element = document.getElementById("div1");
//element.appendChild(listItem[i]);
document.body.appendChild(listItem[i]);
console.log(listItem[i]);
};
};
function addOnClick(j) { //this is separate to handle the closure issue
listItem[j].onclick = function() {loadModal(j)};
};
</script>
However, this code (and several others) produce:
<li href='#modal-one'>Complete Blood Count</li> //note missing <a>...</a>
It appears there are several ways to achieve this, but nothing seems to work for me...
You are never actually adding in an anchor tag. You are creating a list-item (li), but you are adding an href to that list-item rather than adding an anchor node to it with that href. As such, the browser just thinks you have a list-item with an href attribute.
Consider using the following instead:
<script>
var listItem = [];
function createTestList() {
var tests = results.tests; //an array to tests to populate list
var i;
var j; // Never actually used in function. Consider omitting
for (i = 0; i < tests.length ; i++ ){
// create the list item
listItem[i] = document.createElement("li");
// Create the anchor with text
var anchor = document.createElement("a");
var node = document.createTextNode(tests[i].name);
anchor.appendChild(node);
anchor.setAttribute("href", "#modal-one");
// Set the onclick action
addOnClick(i, anchor);
// Add the anchor to the page
listItem[i].appendChild(anchor);
document.body.appendChild(listItem[i]);
console.log(listItem[i]);
};
};
// Modified "addOnClick" to include the anchor that needs the onclick
function addOnClick(j, anch) { //this is separate to handle the closure issue
anch.onclick = function() {loadModal(j)};
};
</script>
A couple things to note:
I have modified your addOnClick() function because it is the anchor element that needs the onclick, not the list item.
I have added in the creation of an anchor element rather than simply creating a list item and adding the href to that.
I do not see creating a element, change code to:
var aNode=document.createElement("a");
aNode.innerText=tests[i].name;
aNode.setAttribute("href", "#modal-one");
listItem[i].appendChild(aNode);
You can change also click method, to use it on a not on li
function addOnClick(j) {
listItem[j].querySelector("a").addEventListener("click",function(e) {
e.preventDefault();//this prevent for going to hash in href
loadModal(j);
});
};
Okay. I missed the anchor tag. My bad...
Spencer's answer came close, but I had to make few changes to get it work in my instance.
The final working code (and honestly I am not sure why it works) is:
<script>
var listItem = [];
function createTestList() {
var tests = results.tests;
var i;
//var j;
for (i = 0; i < tests.length ; i++ ){
// create the list item
listItem[i] = document.createElement("li");
// Create the anchor with text
var anchor = document.createElement("a");
anchor.setAttribute("href", "#modal-one");
var node = document.createTextNode(tests[i].name);
anchor.appendChild(node);
// Set the onclick action
addOnClick(i);
// Add the anchor to the page
listItem[i].appendChild(anchor);
document.getElementById("demo").appendChild(listItem[i]); //added the list to a separate <div> rather than body. It works fine like this.
console.log(listItem[i]);
};
};
function addOnClick(j) { //this is separate to handle the closure issue
//didn't need the additional code beyond this
listItem[j].onclick = function() {loadModal(j)};
};
</script>
Thanks to all and Spencer thanks for the thoroughly commented code. It helps!!!

document.getElementsByClassName('name') has a length of 0

I'm trying to retrieve all the elements by class name by using the method getElementsByClassName (no jQuery). Console.log shows the array of the elements, but when I try to get the length of the array, it returns 0.
Saw a previous post with a similar problem that provided a solution of making sure that the element exists. I took this into consideration and fire the function after DOMcreation.
What is going on here?
document.addEventListener("DOMContentLoaded", function(){
// Load current todo items from db
loadTodoItems();
var submitBtn = document.getElementById('submit-btn');
submitBtn.addEventListener('click', addItem);
var removeButton = document.getElementsByClassName("remove-btn");
console.log(removeButton);
console.log(removeButton.length);
}, false)
Another issue to note, is that I am noticing that in chrome Dev Tools when I look at the head tag, I'm seeing that some sort of angular code is being loaded in a script tag in the head, while the content that should be in my head tag are being loaded in the body. I am not using angular for my app.
Edit. Here is my HTML. It is in Jade:
Layout.jade:
doctype html
html(lang='en')
head
meta(charset="utf-8")
title To Do List
link(rel="stylesheet" href="main.css")
body
block content
script(src="main.js")
index.jade:
extends layout
block content
div.container
h1 Get-Er-Done!
form#todo-form(role="form" method="POST" action="/todo")
div.form-group
label(for="addToDo") Add To-Do item:
input#todoItemText.form-control(type="text")
button(type="submit")#submit-btn.btn.btn-default Add
ul#todo-list
Edit. The remove button is for the new todo item. This is called every time the user clicks add to post the new item.
function renderItems(items){
// Before rendering todo-items, clear the existing items in the list
var list = document.getElementById('todo-list');
while(list.hasChildNodes()){
list.removeChild(list.lastChild);
}
// Loop through items
for (var i = 0; i < items.length; i++) {
var el = document.createElement("li");
var removeBtn = document.createElement('button');
var btnText = document.createTextNode('Done');
removeBtn.appendChild(btnText);
removeBtn.className = 'remove-btn';
var newItemText = document.createTextNode(items[i].item);
el.appendChild(newItemText); // Add new content to new div
el.appendChild(removeBtn);
// To-Do list to append to
list.appendChild(el);
}
}
Length is 0 because when you run it there's no element with class remove-btn. You can see the items in the console because getElementsByClassName returns a live HTMLCollection, which is updated when new elements are added.
The problem is that you create the elements with that class in renderItems, which runs after you run getElementsByClassName.
You can fix it using
function renderItems(items){
var list = document.getElementById('todo-list');
while(list.hasChildNodes()){/* ... */}
for (var i = 0; i < items.length; i++) {/* ... */}
// Load current todo items from db
loadTodoItems();
var submitBtn = document.getElementById('submit-btn');
submitBtn.addEventListener('click', addItem);
var removeButton = document.getElementsByClassName("remove-btn");
console.log(removeButton);
console.log(removeButton.length);
}

Categories

Resources