JavaScript JavaScript and the DOM Traversing the DOM Getting All Children of a Node with children

thomas shellberg
thomas shellberg
4,707 Points

A way to abstract the creation of the buttons(more DRY?)

Not a question but thought I'd share how I abstracted the creation of the buttons a bit in this code. I created a method which returned an element that has a class and textContent based on the parameters passed.

addElement = ( type, className, textContent ) => {
  let element = document.createElement(type);
  element.className = className;
  element.textContent = textContent;
  return element;
}

So, inside of a for loop for the children of the UL element, you can add a button with one line:

let removeButton = addElement('button', 'remove', 'X');

Where 'button' is the element type that the addElement method will create, 'remove' is the className added to the button(which our JS is listening for), and 'X' is just the text within the <button></button> element as a visual indicator to remove the element.

Hope that helps someone and always happy to hear feedback if this approach could be improved. :)

1 Answer

Steven Parker
Steven Parker
153,093 Points

Excellent concept, and good execution! I would only suggest adding "var" or "const" to the creation of "addElement" instead of relying on the implicit global declaration.