remove all dom elements which don't have a "data-key" attribute; store those elements into an array and reappend them into the dom when the document is clicked in javascript

index.tsx
// select all elements without a data-key attribute and store them in an array
const elementsWithoutDataKey = [...document.querySelectorAll(':not([data-key])')];

// remove elements from the DOM
elementsWithoutDataKey.forEach(el => {
  el.remove();
});

// reappend elements to the body when document is clicked
document.addEventListener('click', () => {
  elementsWithoutDataKey.forEach(el => {
    document.body.appendChild(el);
  });
});
441 chars
15 lines

Explanation:

  • We use document.querySelectorAll to select all elements without a data-key attribute. We can filter the elements by using the attribute selector, :not([data-key]). This returns a NodeList, which we convert to an array using the spread operator ....
  • We then use the forEach method to loop through each element in the array of elements without the data-key attribute and remove them from the DOM using the remove() method.
  • Finally, we add an event listener to the document that listens for a click event. When the document is clicked, we loop through the array of elements without the data-key attribute, and reappend them to the body using appendChild().

gistlibby LogSnag