skip to Main Content

I have an forEach, for a document with querySelectorAll.

In there, I have a name and some more variables. Is it possible to Sort the forEach Loop and check if there are words, matching with my array to show these ones first?

So i have a list like that:
 ['vollautomat', 'fernseher']

And i will that items with "name" = vollautomat or fernseher will showed first. Than the others.

document.querySelectorAll(".vvp-item-tile").forEach(function (element, index) {
                    var name = element.querySelector('.a-link-normal').innerText;
console.log(name)
                });

How is it possible to sort the forEach that these will showed first?

I tried to find out with searching but all I found was to short arrays and not a forEach loop with document.querySelecterAll

2

Answers


  1. I would try to convert the NodeList returned by querySelectorAll into an array. Then would sort the array based on the criteria (for instance, if the name matches an item in your list). Finally sort the array.

    // Your list of keywords
    const keywords = ['vollautomat', 'fernseher'];
    const elements = Array.from(document.querySelectorAll(".vvp-item-tile"));
    
    // Sort the elements based on whether the name matches a keyword
    elements.sort((a, b) => {
      const nameA = a.querySelector('.a-link-normal').innerText.toLowerCase();
      const nameB = b.querySelector('.a-link-normal').innerText.toLowerCase();
    
      const isInKeywordsA = keywords.some(keyword => nameA.includes(keyword));
      const isInKeywordsB = keywords.some(keyword => nameB.includes(keyword));
    
      if (isInKeywordsA && !isInKeywordsB) return -1;
      if (!isInKeywordsA && isInKeywordsB) return 1;
      return 0;
    });
    
    const container = document.body;
    container.innerHTML = '';
    
    // Append the sorted elements back to the DOM
    elements.forEach((element) => {
      container.appendChild(element);
      const name = element.querySelector('.a-link-normal').innerText;
      console.log(name); // This will print names in the sorted order
    });
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Sort Example</title>
    </head>
    
    <body>
      <div class="vvp-item-tile">
        <a class="a-link-normal" href="#">Fernseher Samsung</a>
      </div>
      <div class="vvp-item-tile">
        <a class="a-link-normal" href="#">Laptop HP</a>
      </div>
      <div class="vvp-item-tile">
        <a class="a-link-normal" href="#">Vollautomat DeLonghi</a>
      </div>
      <div class="vvp-item-tile">
        <a class="a-link-normal" href="#">Smartphone Apple</a>
      </div>
      <div class="vvp-item-tile">
        <a class="a-link-normal" href="#">Kaffeemaschine Philips</a>
      </div>
    </body>
    
    </html>
    Login or Signup to reply.
  2. Since there’s no HTML I’m assuming that the selector: ".vvp-item-tile" is unnecessary and ".a-link-normal" is sufficient. Run the function from the example below with the following parameters:

    prioritizeText(".a-link-normal", "vollautomat", "fernseher");
    

    Details are commented in the example.

    // A utility function for demonstration purposes
    const log = data => console.log(JSON.stringify(data));
    
    /**
     * This extracts the text from a given group of DOM elements
     * and returns them as an array. Any matches from the given list
     * of keywords will be listed first in the returned array.
     * @param {string} selector - CSS selector of the targeted elements
     * @param {...string} ...keywords - A comma delimited list of strings 
     *                                  of the text to find.
     */
    /* ...keywords is a rest parameter, any number of strings may be passed.
     * When passed into the function ...keywords is an array.
     */
    function prioritizeText(selector, ...keywords) {
      // Collect all elements matching selector into an array.
      const elements = Array.from(document.querySelectorAll(selector));
      console.log("elements:")
      console.log(elements);
      // Define two empty arrays, one for matched text and one for the rest.
      let A = [];
      let B = [];
      // For each ele in elements...
      elements.forEach(ele => {
        // extract text from ele...
        const text = ele.textContent;
        // If any string of keywords array matches the text...
        if (keywords.includes(text)) {
          // add text to the first empty array...
          A.push(text);
        } else {
          // otherwise add text to the second empty array.
          B.push(text);
        }
      });
      console.log("first array:")
      log(A);
      console.log("second array:");
      log(B);
      // Merge the two arrays into one array by the spread operator "..."
      console.log("result:");
      return [...A, ...B];
    }
    
    log(prioritizeText("a", "C", "F"));
    <a href="#">A</a>&nbsp;
    <a href="#">B</a>&nbsp;
    <a href="#">C</a>&nbsp;
    <a href="#">D</a>&nbsp;
    <a href="#">E</a>&nbsp;
    <a href="#">F</a>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search