Search code examples
javascriptsortingappendchild

How to get attribute inside a tag in Javascript for sorting function


i found this function which is working good but i need something a little more specific:

    function sortList() {
  var ul = document.getElementsByClassName("myUL")[0];
    
  Array.from(ul.getElementsByTagName("li"))
    .sort((a, b) => a.getAttribute('title').localeCompare(b.getAttribute('title')))
    .forEach(li => ul.appendChild(li));
}

So, i need to getAttribute title but from img tag which is inside my li instead of the li itself and i don't know ho to do this. Sorry for the stupid question but i'm a total noob just trying to create a simple archive for personal use.


Solution

  • Use Element.closest()

       function sortList() {
          var ul = document.getElementsByClassName("myUL")[0];
          Array.from(ul.getElementsByTagName("li"))
            .sort((a, b) => a.querySelector("img").getAttribute('title').localeCompare(b.querySelector("img").getAttribute('title')))
            .forEach(li => ul.appendChild(li));
        }