Filter and sort tags using Javascript

Asked

Viewed 203 times

0

I need to make a filter using pure Javascript.

But by doing the filter and sorting by Name (a, b), for example, I can only sort the text elements out of context and not the complete block.

For example:
I need that block <div class="item"> be ordered along with <span>:

<div id="produto">
<div class="item">
  <span class="titulo">C</span>
</div>
<div class="item">
  <span class="titulo">B</span>
</div>
<div class="item">
  <span class="titulo">A</span>
</div>

The code I have is this:

    window.onload=function(){
      var div = document.querySelector('#produto'),
      para = document.querySelectorAll('.item span.titulo');
      var paraArr = [].slice.call(para).sort(function (a, b) {
        return a.textContent > b.textContent ? 1 : -1;
      });
      paraArr.forEach(function (p) {
       div.appendChild(p);
  });
    }
 .item{
      display: block;
      border: 1px solid #DFDFDF;
      padding: 8px;
      margin: 8px;
    }
<!DOCTYPE html>
<html>
<body>
  <div id="produto">
    <div class="item">
      <span class="titulo">C</span>
    </div>
    <div class="item">
      <span class="titulo">B</span>
    </div>
    <div class="item">
      <span class="titulo">A</span>
    </div>
  </div>
</body>
</html>

1 answer

0


"Sort" html directly is more complicated than generating a new one based on data you have. And it even happens that in your case you end up doing appendChild to add an element that already exists in the place where it is being added but not as a direct child but as a grandchild. It also has no direct way to sort one element and move another, in case it sorts the titulo and take the item, without being navigating the DOM. Moreover, if the ordination is to be made on texts then it must be based on the localeCompare.

Simpler would be to have an array of titles or something that represents the information you have to display, and a way to generate the corresponding html. Then you just need to sort the array and recreate the html.

Example:

const titulos = ["B", "C", "A"];

window.onload = function() {
  const divProduto = document.getElementById("produto");
  
  //função que cria o html de cada titulo
  const htmlTitulo = (titulo) => {
    return `<div class="item">
              <span class="titulo">${titulo}</span>
            </div>`;
  };
  
  //função que constroi o html total do produto "mapeando" cada titulo 
  //no seu html e juntando tudo para colar no div produto
  const mostrar = () => divProduto.innerHTML = titulos.map(htmlTitulo).join("");
  
  document.getElementById("crescente").addEventListener("click", () => {
    titulos.sort((a, b) => a.localeCompare(b)); //ordenação com localeCompare
    mostrar();
  });
  
  document.getElementById("decrescente").addEventListener("click", () => {
    titulos.sort((a, b) => b.localeCompare(a)); //ordenação com localeCompare
    mostrar();
  });
  
  mostrar(); //quando carrega inicialmente também mostra
}
.item {
  display: block;
  border: 1px solid #DFDFDF;
  padding: 8px;
  margin: 8px;
}
<!DOCTYPE html>
<html>
<body>
  <div id="produto"></div>
  <button id="crescente">Crescente</button>
  <button id="decrescente">Decrescente</button>
</body>
</html>

  • Thanks :D really create the elements ends up becoming easier

Browser other questions tagged

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