I know it is a very easy question but I am still struggling. I created a function which adds element
in an Array
and after that I am using forEach
loop for appending them in the DOM. But I am unable to prevent addition of 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>
What I have tried 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!!