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
Marlon bs is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
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>