I have been working on a single page application in Javascript and would like to implement a sort by names and popularity of cards created by some data fetched from Movie DB API. I have already tried to use the code below to sort the elements and append them on the page but have been struggling with it.
Thanks in advance for your time reading and helping me with this. I do really appreciate it!
const SORT = { namesArr:[], name:(ev)=>{ //avoiding the popstate event to be triggered ev.preventDefault(); //getting the pages content let page= document.querySelector('#actors'); //getting the parent Element on the page let items= document.querySelector('.cards'); //converting the elements into an array items= Array.prototype.slice.call(items.children); console.log(items) //sorting the elements items.sort(function (a, b) { //getting the name inside each card. varA= a.name.toUpperCase(); varB= b.name.toUpperCase(); if (varA < varB){ return -1; } if (varA > varB){ return 1; } return 0; }); //iterating over the elements to append it on the page. for(i = 0; i < items.length; i++){ page.appendChild(items[i]); } }, };
<section id= "actors" class="active"> <div class="cards"> <div class="card" data-key="18897"><img class="picture" src="https://image.tmdb.org/t/p/w300/nraZoTzwJQPHspAVsKfgl3RXKKa.jpg"><h3 class="name">Jackie Chan</h3><p class="popularity">Popularity: 28.744</p></div> <div class="card" data-key="1173223"><img class="picture" src="https://image.tmdb.org/t/p/w300/hkHu1Z4EtN47bPwh6PlBIE3Jz76.jpg"><h3 class="name">Danny Chan Kwok-Kwan</h3><p class="popularity">Popularity: 15.431</p></div> </div> </section>
Advertisement
Answer
I believe you want to sort the cards
const cards = document.querySelector("#actors .cards"); const children = [...cards.children]; children.sort((a, b) => { return a.querySelector(".name").innerText > b.querySelector(".name").innerText ? 1 : -1; }) cards.innerHTML = ""; children.forEach(item => cards.appendChild(item));
<section id="actors" class="active"> <div class="cards"> <div class="card" data-key="18897"><img class="picture" src="https://image.tmdb.org/t/p/w300/nraZoTzwJQPHspAVsKfgl3RXKKa.jpg"> <h3 class="name">Jackie Chan</h3> <p class="popularity">Popularity: 28.744</p> </div> <div class="card" data-key="1173223"><img class="picture" src="https://image.tmdb.org/t/p/w300/hkHu1Z4EtN47bPwh6PlBIE3Jz76.jpg"> <h3 class="name">Danny Chan Kwok-Kwan</h3> <p class="popularity">Popularity: 15.431</p> </div> </div> </section>