Home > Enterprise >  All texts in HTML elements should have a new line character['\n']
All texts in HTML elements should have a new line character['\n']

Time:08-31

Every text value inside an HTML element needs a new line character. Here is the dart method I used to do it. However, it failed to add new lines for the given type of HTML elements. I would like to know how can I change this method which can success for all types of cases.

Thanks in advance.

Code

  dom.Element loop(dom.Element node){
    
    final List<dom.Element> elements = node.children;
    for (int i = 0; i < elements.length; i  ){

      if(elements[i].hasContent() && elements[i].children.isEmpty){
        elements[i].innerHtml = '${elements[i].text}\n';
        continue;
      } else

      if(elements[i].children.isNotEmpty){
        loop(elements[i]);
      }
    }
   return node;
  }

Input HTML element

<div>
   <ul>
      <li>test1</li>
      <li>
         test2
         <ul>
            <li>
               &nbsp;test3
               <ul>
                  <li>test4</li>
                  <li>test5</li>
               </ul>
            </li>
            <li>test6</li>
         </ul>
      </li>
      <li>test7</li>
   </ul>
</div>

Expected result

<div>
   <ul>
      <li>test1\n</li>
      <li>
         test2\n
         <ul>
            <li>
               &nbsp;test3\n
               <ul>
                  <li>test4\n</li>
                  <li>test5\n</li>
               </ul>
            </li>
            <li>test6\n</li>
         </ul>
      </li>
      <li>test7\n</li>
   </ul>
</div>

CodePudding user response:

Here is a javascript implementation of the answer (You can change it to dart easily)

function loop(node) {
    const elements = node.children
    for(const element of elements) {
        if(element.children.length > 0) loop(element)
        else if(element.textContent.length > 0) {
            element.innerHTML = element.textContent   " \\n "
        }
    }
}

This works except it won't change the text of a parent node. If you add \n to a parent node like li2 you will get the \n after everything including its children, there is no way to just select that initial text that I can see. You may need to do more research in that area.

The output of the above function.

<div>
   <ul>
      <li>test1\n</li>
      <li>
         test2
         <ul>
            <li>
               test3
               <ul>
                  <li>test4\n</li>
                  <li>test5\n</li>
               </ul>
            </li>
            <li>test6\n</li>
         </ul>
      </li>
      <li>test7\n</li>
   </ul>
</div>
  • Related