javascriptalgorithmdom-traversal

How to find all text and his parent inside a DOM element


I can't find a way to get node siblings that contain only tabs so I can throw them away and get text only and his parents.

<html>
<head><title>My page</title></head>
<body>

  <div id="container">
    <div id="subject">
      <div> divText <span>
        <a> aText </a>
        spanText </span>
      </div>
    </div>
  </div>

  <script>

    var subject = document.getElementById('subject');

    function printInnerText(ele)
    {
        var childrens = ele.childNodes;

        if (childrens.length > 1)
        {
            for (var i = 0; i < childrens.length; i++)
            {
                printInnerText(childrens[i]);
            }
        }
        else
        {
            console.log(ele.innerText);
        }
    }

    printInnerText(subject);

  </script>
</body>
</html>

if "#text" contanins textContent (and wholeText) as an enter or tabs only I need to move to next node.nextSibling. I need to find text only and his parents.

BTW on ie innerText give me only text without tabs, but I have discover that chrome works different.


Solution

  • A recursive approach for do this (based on your original try) will be to check for nodeType equal to type Node.TEXT_NODE while you are traversing the descendants, when you found a text, then you can use trim() to check the existence of a non-empty text, in this particular case, you can get the parent and the related text. As shwon on next example:

    var subject = document.getElementById('subject');
    
    function clasifyTextByWrapper(ele)
    {
        if (ele.nodeType === Node.TEXT_NODE && ele.nodeValue.trim())
            console.log(ele.parentNode.nodeName + " contains text: " + ele.nodeValue.trim());
    
        ele.childNodes.length && ele.childNodes.forEach(e => clasifyTextByWrapper(e));
    }
    
    clasifyTextByWrapper(subject);
    <div id="container">
      <div id="subject">
        <div> divText <span>
          <a> aText </a>
            spanText </span>
        </div>
      </div>
    </div>