Error alert: items.appendChild does not function

I'm running into an issue while trying to add buttons to the existing list items. Below is my code snippet:

function buttonDelete() {

var items = document.getElementsByTagName("li");
var button = document.createElement("button");
button.appendChild(document.createTextNode("Delete"));
items.appendChild(button);
button.onclick = function() {
this.remove();
items.remove();
}
}
buttonDelete();

Unfortunately, I keep encountering an error message: Uncaught TypeError: items.appendChild is not a function.

When I try selecting only one li item (var items = document.querySelector("li");), it successfully adds the button but only for the first item in the list.

Answer №1

document.getElementsByTagName method retrieves a collection of all elements in the document that have the specified tag name, returned as a NodeList.

To implement this, you will need to create a loop and add a button element for each item in the collection.

var items = document.getElementsByTagName("li");
Array.from(items).forEach(elem => {
  var button =document.createElement("button");
  button.appendChild(document.createTextNode("Delete"));
  button.onclick = function() {
      this.parentElement.remove();
  }
  elem.appendChild(button);
});
<ul>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

Answer №2

If you use the getElementsByTagName method in JavaScript, it will give you an HTMLCollection of li elements. To add a button to each of these li elements, you'll need to loop through them individually.

const items = document.getElementsByTagName("li");
Object.values(items).forEach((li,i)=>{
   const but = document.createElement("button");
   but.innerHTML = i;
   li.appendChild(but);
});
<ul>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I retrieve the internal variable from a state using the onClick event?

I am facing an issue with my react app. Whenever I push the button, the results are not showing up as expected: test While it works fine for null values, I am unable to display the result of the getNewResult function!! import React from 'react'; ...

What is the best way to separate an ellipse into evenly sized portions?

This function is used to determine the coordinates of a vertex on an ellipse: function calculateEllipse(a, b, angle) { var alpha = angle * (Math.PI / 180) ; var sinalpha = Math.sin(alpha); var cosalpha = Math.cos(alpha); var X = a * cosa ...

What is the best way to wait for a button's listeners to resolve in JavaScript?

Currently, I am conducting frontend tests utilizing Jest with the jsdom environment to simulate a DOM tree and manually trigger actions such as button.click(). My goal is to be able to await button.click(), which in my expectations should wait for all of ...

What are the steps to integrate openjphjs with next.js?

I am working on a project with Next.js and need to utilize openjphjs for decoding HTJ2K pixel data. In order to incorporate openjphjs, I have included both openjphjs.js and openjphjs.wasm in a specific folder within the project structure. To address an e ...

Unable to utilize a function within a mongoose schema

I encountered an issue while attempting to access the schema methods of a mongoose schema in TypeScript. Schema const userSchema: Schema<IUser> = new Schema( { name: { type: String, required: [true, "Name is required"], ...

Is There a Workaround for XMLHttpRequest Cannot Load When Using jQuery .load() with Relative Path?

My current project is stored locally, with a specific directory structure that I've simplified for clarity. What I'm aiming to do is include an external HTML file as the contents of a <header> element in my index.html file without manually ...

What is the best way to retrieve multiple JSON files from a single directory using React?

I am currently working on a React project which includes a folder titled "data" within the src directory. Inside this data folder, there are multiple JSON files that I need to fetch. The issue is that I do not know the names of these JSON files. How can ...

Error message with ThreeJS ObjectLoader: "unable to interpret the 'fog' property as it is not defined"

Currently, my setup involves using ThreeJS to import a scene as shown in the code snippet below: $(document).ready(function(){ var scene = new THREE.ObjectLoader().load("scene.js"); var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / ...

What is causing fs.readFileSync to not recognize my json document?

So, I've been working on creating a Discord bot that can extract specific data from my JSON file. Here is the structure of my project: Project | +-- data/ | | | +-- compSciCourses.json | +-- src/ | | | +-- search.js | +-- bot.js | +-- t ...

"Experience the power of Vue.js 3.2 with Dynamic Component Knockout

I am trying to use a dynamic component to update my section, but when I click on my sidebar ('nav'), it doesn't change. Even though route.params.current changes, the component is not loaded. <template> <q-page class="contain ...

Select a color at random from the array, animate it, then repeat the process by selecting a new random color from the

Currently, I am utilizing gsap and three js to animate a light source. I have an array containing various colors that I would like to cycle through randomly during the animation process. My objective is to continuously loop through the random color selec ...

An issue arises with React hooks: useMemo and useEffect display a Missing dependency error when attempting to invoke a function

triggerData function is being utilized in multiple functions. However, if I place the function inside the useEffect to prevent missing dependencies, then I am unable to call the triggerData outside of the useEffect i.e., in buildData. How can I resolve the ...

Obtaining Navigation Parameters within Custom React Navigation Title

In the React Navigation StackNavigator, I created a custom title that looks like this: const CustomStackNavigator = StackNavigator({ Home: { screen: HomeScreen } }, { navigationOptions: { headerTitle: <GradientHeader title={this.props.nav ...

Looking to retrieve the numerical values from a given array

I have a set of data in the following format: ['32 68', '56 78', '77 99'] I am looking to output another set of data that will consist of the sums of each pair of numbers by index using JavaScript in NodeJS. For example, [& ...

Display Error with Custom Alert Box

I recently implemented a customized alert box from slayeroffice's website, which you can find at slayeroffice.com/code/custom_alert/. When I view it on my browser, the alert box appears with a blue color in the center of the screen. Here is how it lo ...

How does the "deliver_order" function retrieve the value of the name parameter?

function take_order(name, callback1) { console.log("order has been taken."); callback1(name); } function prosess_order(name, callback2) { console.log(`prosesing order for ${name}.`); callback2(name); } function deliver_order(name) { console.log ...

Mongoose: No documents are being returned by the .find() method

UPDATE : Similar question posted here: Trouble with Mongoose find() method I'm still new to working with nodejs and nosql databases. Today, I am building an API that retrieves data from my user collection which currently has two entries : https://i. ...

What causes the excessive memory usage of (JS)Strings when loading complex .obj files in AFrame and Three.js?

Our webscene is quite complex, with dynamically loaded .obj and .mtl files. When comparing the scene without any objects to one with multiple objects, we noticed a strange issue: In Firefox's memory heap, most of the memory (>100MB for 5 objects) ...

Having trouble accessing deployed HTML and JavaScript files on an Azure Web App?

As a newcomer to Azure, I hope you can bear with me if I ask a basic question. Is it possible to manually deploy a project built with HTML and vanilla JavaScript to an Azure Web App (not Azure Static Web App)? I have successfully deployed my files to a W ...

What is the process for converting variables from browser script to Python code?

I ran the script below in my browser webdriver.execute_script("document.getElementsByClassName('bulk_item').length") My goal is to have the number that the script returns stored in a variable called elem for easy access. However, simp ...