Avoiding the inclusion of repetitive elements in the DOM

I am facing a simple issue that I can't seem to figure out. I have written a function that adds an element to an Array, and then uses a forEach loop to append them to the DOM. However, I'm struggling to avoid adding duplicate elements.

const btn = document.querySelector("button");

btn.addEventListener("click", () => {
  addItem(btn.innerText);
});

function addItem(item) {
  let items = [];

  if (!items.includes(item)) {
    items.push(item);
  }

  items.forEach((element) => {
    const li = Object.assign(document.createElement("li"), {
      innerText: element
    });

    document.body.appendChild(li);
  });
}
@import url("https://cdn.jsdelivr.net/gh/KunalTanwar/organise.css/css/organise.inter.min.css");
body {
  display: grid;
  place-items: center;
}

button {
  border: 0;
  background: none;
  padding: 1rem 2rem;
  box-shadow: inset 0 0 0 1px gray;
}
<button> Add Me </button>

My attempts so far :

[...new Set(items)].forEach((element) => {
  const li = Object.assign(document.createElement("li"), {
    innerText: element
  });

  document.body.appendChild(li);
});

Another Method -

if (!items.includes(item)) {
  items.push(item);
} else {
  return
}

lastly -

if (!items.includes(item)) {
  items.push(item);
} else {
  items = [...new Set(items)]
}

But still no luck!!

Answer №1

items should have a global scope by being declared outside of the function. Currently, it is being initialized as an empty array inside the function on each call, causing it to lose track of existing items. Additionally, make sure to include a return statement in your function when the value is already in the array. I also made adjustments for multiple buttons by adding event listeners to all buttons.

const btns = document.querySelectorAll("button");
let items = [];
btns.forEach(b => b.addEventListener("click", () => {
     addItem(b.innerText);
}));

function addItem(item) {
  if (!items.includes(item)) {
     items.push(item);
  } else {
     return;
  }

  
  const li = Object.assign(document.createElement("li"), {
     innerText: item
  });

  document.body.appendChild(li);
  
}
@import url("https://cdn.jsdelivr.net/gh/KunalTanwar/organise.css/css/organise.inter.min.css");
body {
  display: grid;
  place-items: center;
}

button {
  border: 0;
  background: none;
  padding: 1rem 2rem;
  box-shadow: inset 0 0 0 1px gray;
}
<button>Add Me</button>
<button>Add Me Again</button>

Answer №2

Make sure to redefine items only once, instead of every time, to avoid resetting it and checking against an empty array.

When looping over the array, remember to only append the element you are adding to prevent adding duplicate elements.

// Improved example with multiple buttons
const btns = document.querySelectorAll("button");
btns.forEach(btn => {
  btn.addEventListener("click", () => {
    addItem(btn.innerText);
  });
});

// Separated out the rendering code for reusability in other places
function renderItem(innerText) {
  const li = Object.assign(document.createElement("li"), {
    innerText
  });
  document.querySelector("#out").appendChild(li);
}

// Declare items outside the method to retain values
// Included default values for demonstration
const items = ["d1", "d2"];

// Render items from the array, useful for default or localstorage data
items.forEach(renderItem);

// Function triggered by click event to add items to UI
function addItem(item) {
  // Check if item already exists, exit if true
  if (items.includes(item)) return;

  // Add the new item
  items.push(item);

  // Display the added item
  renderItem(item);
}
@import url("https://cdn.jsdelivr.net/gh/KunalTanwar/organise.css/css/organise.inter.min.css");
body {
  display: grid;
  place-items: center;
}

button {
  border: 0;
  background: none;
  padding: 1rem 2rem;
  box-shadow: inset 0 0 0 1px gray;
}
<button type="button"> Add Me 1</button>
<button type="button"> Add Me 2</button>
<button type="button"> Add Me 3</button>

<ul id="out"></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

Creating a gaming application with Phaser.js and Ionic with subpar rendering capabilities

Attention developers! I recently created a game app using Phaser.js. I integrated the code into an Ionic blank starter app, allowing the Ionic framework to render the view while Phaser takes care of displaying the game. Issue: The game is a simple flapp ...

What do I do when I get a "findByIdAndUpdate is not a function" error from my controller after requiring the model

I am currently developing a web application for my company that allows us to access and manage a database of customers and their information using MongoDB, Mongoose, and Express. Our company specializes in reselling used copiers/printers and offering maint ...

Separate individual digits from a number and assign them to an array

Looking to store all the individual digits of a number in an array? For example, taking 2017 and creating a vector V = [2, 0, 1, 7]. Here's the code snippet: import array n = 2017 sizeN = 4 m = n i = 1 V = [] while m!=0: ...

wrap <td> data in a link with vue depending on certain conditions

I'm trying to customize the display of a particular table cell td. I want to show the data in a link if a certain condition is met, and if not, just show the data as text. However, I'm encountering some difficulties in implementing this. I have ...

Implementing Angular's ngModel directive within an conditional statement

As a newcomer to Angular, I am attempting to write code that will display a list of checkboxes. My goal is to only show checked checkboxes in the list and not display unchecked ones. I am using ngModel to retrieve data from an interface. I attempted to use ...

Error: Unable to access 'map' property of an undefined variable in ReactJS

Hello everyone, I'm struggling to understand why I keep getting this error when trying to retrieve data from the Covid19 API. It returns an object that contains a Countries array, but when I try to map over the Countries, I encounter an error. However ...

Error: Failed to parse the given color specification

My chrome extension is showing an error message: Unchecked runtime.lastError: The color specification could not be parsed. This error seems to be in the popup.html: 1 -> <! DOCTYPE html> line. Can anyone explain what this means and how to fix ...

Discovering whether x is equal to any value within an array using JavaScript

I am seeking a way to modify my current if statement, which looks like this: if (x==a||x==b||x==c||x==d||x==e) { alert('Hello World!') }; Is there a method to test whether x matches any of the values in an array such as [a,b,c,d,e]? Your as ...

Discover the best approach for transforming a complicated JSON object/array into a map using inheritance coding techniques

Could someone help me with creating an array of objects (only 1 level) based on the following JSON structure? [ { 'family' : { 'name' : 'Doe', 'from' : 'Foo' }, ...

Experiencing difficulty navigating the operations of insertion, deletion, and search within a string array concurrently

When attempting to incorporate insert, delete, and linear search functionalities into a string array in the same code, I encountered an issue with the insertion operation. Although delete and linear search are functioning correctly, the insertion operation ...

Guide to extracting a sub-string array from a string array in C#

Just starting out with c# and I've encountered an issue. I have a string that needs to be split into a string array, but one of the elements must be split again as it is parsed differently. My goal is to convert these string arrays into float arrays ...

Ways to implement the data from xmlhttp.responseText

I need help with executing a function that I retrieve from an xmlhttp response. The content of the response is a block of JavaScript code similar to: setChatter('".$name."');showHideLayer('chatFenster');return(false); How can I proper ...

Creating a pop-up window displaying event details when a user hovers over or clicks on an event in fullcalendar using JavaScript

I have been struggling for a while now, attempting every possible way to add a popup window on mouse hover using fullcalendar. Sadly, all the solutions I've tried either mess up my calendar or don't work at all. I am trying to implement a popup w ...

Alert: An issue was encountered with React instrumentation: Error: It is advised that the children do not change when passing in the same set - nextjs

I keep seeing this error message in the console when navigating between pages. Even though I believe I'm not utilizing the same component on both pages, This seems to be a new issue possibly related to React19, but I can't confirm it yet. Any ...

Detecting text overflow with ellipsis in HTML

I am facing an issue with certain elements on my webpage that have the CSS properties white-space, overflow, and text-overflow set in a way that causes text overflow to be trimmed with an ellipsis. div { white-space: nowrap; text-overflow: ellipsis; ...

Error: The cordovaLocalNotification plugin is attempting to read a property 'plugins' that is undefined, resulting in a TypeError

I am currently working on a hybrid application using the Ionic platform. I am trying to integrate Cordova local notification features, but I keep getting an error message saying "cannot read property 'plugins' of undefined." Below is my code. Can ...

Encountering Issues with Script functionality on secure websites

I tried running this code on my development machine and it worked perfectly fine over http. However, as soon as I switched to https, it stopped functioning. Any assistance on this matter would be highly appreciated. The code I am using is from zippopotamu ...

How can I determine the appropriate time to hide the loading screen after the model has been loaded with gltfLoader and before the scene is rendered?

I am currently working on a project using threejs version 106, where I have integrated both the webGLRenderer and CSS2DRenderer. My main challenge lies in loading a glb model and displaying a loading progress bar utilizing the onProgress callback of the l ...

Error: Cannot locate 'import-resolver-typescript/lib' in jsconfig.json file

Issue: An error occurred stating that the file '/Users/nish7/Documents/Code/WebDev/HOS/frontend/node_modules/eslint-import-resolver-typescript/lib' could not be found. This error is present in the program because of the specified root file for c ...

Utilizing the Google Translate API within an ASP MVC framework to translate a div's content from English to Arabic

Currently, I am working on a small project that involves two divs: one for English and another for Arabic. Despite creating the project, I am encountering an issue with getting the translation from English to Arabic. Below is the code I have attempted, but ...