How to distribute elements in class hierarchy by dividing by aligned element?

Asked

Viewed 39 times

0

Imagine you have a parent element with children where the class represents a text selection:

<span class="item-1" data-id="1">texto selecionado 1
     <span class="item-2" data-id="2">texto selecionado 2
         <span class="item-3" data-id="3">parte do texto 3</span>
     </span>parte do texto 1
</span>

How could I make these elements stay this way, with some method in Javascript:

<span class="item-1" data-selection="1" data-id="1">texto selecionado 1</span>
<span class="item-2" data-selection="2" data-id="2">texto selecionado 2</span>
<span class="item-3" data-selection="3" data-id="3">parte do texto 3</span>
<span class="item-1" data-selection="4" data-id="1">parte do texto 1</span>

1 answer

1


You can use a recursive function that will traverse the main element nodes (class span .item-1) using the method .childNodes, that selects all element nodes, either text or tags. If you find a tag in the middle of the way, you will go through the nodes of that tag as well, creating an array where the new HTML will be mounted organized in the desired way to be inserted into a container. So you need to create a span that will serve as a container to replace HTML.

The attribute data-selection will be incremented by the variable idx that begins with the value 1. The other attributes are taken from the text parent element.

Behold:

function organiza(){
   
   var no = document.querySelector('.item-1');
   var html = "", idx = 1;
   
   function recursor(n){

      var a = [];

      if(n.nodeType != 3 && n.childNodes){

         for(var i = 0; i < n.childNodes.length; ++i){
            a = a.concat(recursor(n.childNodes[i]));
         }

      }else if(n.data.trim()){

         html += '<span class="'+ n.parentNode.className +'"'
         +' data-selection="'+ idx +'"'
         +' data-id="'+n.parentNode.dataset.id +'">'
         + n.data.trim()
         +'</span>';
         idx++;

      }

      return a;

   }

   recursor(no);
   document.querySelector(".container").innerHTML = html;
   
}

// inicia a função quando o DOM estiver pronto
document.addEventListener("DOMContentLoaded", organiza );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="container">
   <span class="item-1" data-id="1">
      texto selecionado 1
      <span class="item-2" data-id="2">
         texto selecionado 2
         <span class="item-3" data-id="3">
            parte do texto 3
         </span>
      </span>
      parte do texto 1
   </span>
</span>

Upshot:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.