Home > OS >  Links not changed after alphabetically sorting
Links not changed after alphabetically sorting

Time:03-30

I have a list that is sorted alphabetically, but links from each li are not changing if I verify the elements links after sorting. Can't figure out what am I missing.

Any help with explanations would be greatly appreciated.

My code in HTML:

<ul  id="testingList">
  <li ><a  href="https://www.example.com/info/1" target="_blank">
      <div >
        <div >
          <h3 >Pink</h3>
        </div>
      </div>
    </a>
  </li>
  <li ><a  href="https://www.example.com/info/2" target="_blank">
      <div >
        <div >
          <h3 >White</h3>
        </div>
      </div>
    </a>
  </li>
  <li ><a  href="https://www.example.com/info/3" target="_blank">
      <div >
        <div >
          <h3 >Brown</h3>
        </div>
      </div>
    </a>
  </li>
</ul>

My JS code:

let pickList = document.querySelector("#testingList");

let li = pickList.querySelectorAll("a");

resultList = [];

for (let i = 0; i < li.length; i  ) {
  resultList.push(li[i].innerHTML);
  console.log(resultList);
}

resultList.sort();

for (let j = 0; j < li.length; j  ) {
  li[j].innerHTML = resultList[j];
}

CodePudding user response:

You are rewriting the innerHTML of the <a> elements, but not changing their .href attributes. It might be simpler to just move the elements around instead of rebuilding them.

let pickList = document.querySelector("#testingList");

let lis = [...pickList.querySelectorAll("li")];

lis.sort((a, b) => {
  // sort on the text of the h3 elements contained within
  const asort = a.querySelector('h3.top-box__title').innerText;
  const bsort = b.querySelector('h3.top-box__title').innerText;
  return asort.localeCompare(bsort);
});

// append each li to the list in order
lis.forEach(li => pickList.appendChild(li));
<ul  id="testingList">
  <li ><a  href="https://www.example.com/info/1" target="_blank">
      <div >
        <div >
          <h3 >Pink</h3>
        </div>
      </div>
    </a>
  </li>
  <li ><a  href="https://www.example.com/info/2" target="_blank">
      <div >
        <div >
          <h3 >White</h3>
        </div>
      </div>
    </a>
  </li>
  <li ><a  href="https://www.example.com/info/3" target="_blank">
      <div >
        <div >
          <h3 >Brown</h3>
        </div>
      </div>
    </a>
  </li>
</ul>

  • Related