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!!