skip to Main Content

I have method at my front-end, where I get HTML in string from back end

Here is it

private async tryGetOooMessage(employeeId: string): Promise<string> {
    try {
      return await firstValueFrom(this.messages.getOutOfOfficeInternalMessage(employeeId));
    } catch (e) {
      return '';
    }
  }

Result is:

<div dir="ltr">
    <span>
        <br>
    </span>
</div>
<div dir="ltr">
    <span>
        <br>
    </span>
</div>
<div dir="ltr">
    <span>Dear colleagues!&nbsp;I would like to have a vacation from&nbsp;14/06/2023 to 15/06/2023</span>
</div>
<div>
    <p></p>
</div>

I need to delete all empty divs before not empty. I mean all divs at start that has this

<div dir="ltr"><span><br> </span></div>

How I can do this correctly?

2

Answers


  1. Depends a bit on the larger context, but I think this should get your started:

    const divs = document.getElementsByTagName('div');
        
    for (let i = 0, len = divs.length; i < len; ++i) {
      if (divs[i] && !divs[i].textContent.match(/S/)) {
        divs[i].remove();
      }
    }
    

    https://www.w3schools.com/jsref/jsref_regexp_whitespace_non.asp

    The S metacharacter matches non-whitespace characters.

    Whitespace characters can be:

    • A space character
    • A tab character
    • A carriage return character
    • A new line character
    • A vertical tab character
    • A form feed character
    Login or Signup to reply.
  2. this code will correctly remove div elements that have no content, including those that only consist of whitespace characters. Iterate over the div elements in reverse order (from last to first) to avoid issues with modifying the DOM while iterating.

    <script>
    document.addEventListener("DOMContentLoaded", function () {
        const elements = document.getElementsByTagName("div");
        for (let i = elements.length - 1; i >= 0; i--) {
            const div = elements[i];
            const hasText = div.textContent.trim().length > 0;
            if (div.textContent.trim().length === 0) {
                div.parentNode.removeChild(div);
            }
        }
    });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search