dev

Utility Function: `removeElement`


removeElement is utility function that removes a specific element from the DOM. It is built on top of another function, getElement that I discuss here. This is another example of creating small functions that do one thing well, and leverage other functions to help abstract the complexity.

function removeElement(selectorOrElement) {
  const element = getElement(selectorOrElement);
  element.remove();
}

Above is the simplified version of removeElement. It accepts a css selector or an element (thanks to getElement) and removes it from the DOM. This alone is beneficial, especially with the safety checks in getElement, but we can add a few more checks specifically to help QA go even smoother.

function removeElement(selectorOrElement) {
  const element = getElement(selectorOrElement);

  // Check if the element is found in the DOM
  if (element) {
    element.remove();
  } else {
    console.log(
      `❌ QA removeElement Error: element not found ` + selectorOrElement,
    );
  }
}

Now we’ve added a check to see if the element is in the DOM, and if not, we log a message saying specifically what function failed, and what the input was. getElement also logs if an element cannot be found, but on a single page it can be hard to track down which function failed. Providing a more specific error message makes QA quicker, narrowing the scope to only removeElement. Let’s take it one step further.

function removeElement(selectorOrElement) {
  try {
    // Use getElement function to get the element and check if it is a string or an HTMLElement
    const element = getElement(selectorOrElement);

    // Check if the element is found in the DOM
    if (element) {
      element.remove();
    } else {
      throw new Error(`element not found ` + selectorOrElement);
    }
  } catch (error) {
    // Log any errors that occur
    console.log("❌ QA removeElement Error:", error.message);
  }
}

Finally we add a try catch to removeElement to catch any errors that may occur. This is a more modern way of handling errors in JavaScript, and allows for more flexibility to add more checks in the future if needed.

Usage

Simply pass a css selector or an element.

removeElement(".card");

You may note “Hey buddy, you’re doing a console.log instead of consol.error. What gives?” The sites I work on (which I have no direct control over) log a lot of errors and it’s difficult to find my specific errors. I use console.log log instead with emojis to make my errors stand out.