如何在下载量最高的download_count类div内添加子div?
Solution
Here's a straightforward script that will find the div with the highest download count and add the "most-downloaded" label to it:
// Get all download count divs const downloadDivs = document.querySelectorAll(".download_count"); let maxCount = -1; let mostDownloadedDiv = null; // Loop through each div to find the one with the highest count downloadDivs.forEach(div => { // Extract the numeric value from the div's text (trim whitespace first) const count = parseInt(div.textContent.trim(), 10); // Update max count and corresponding div if current count is higher if (!isNaN(count) && count > maxCount) { maxCount = count; mostDownloadedDiv = div; } }); // If we found a valid div, add the label if (mostDownloadedDiv) { const label = document.createElement("div"); label.className = "most-downloaded"; label.textContent = "Most downloaded file on the website!"; mostDownloadedDiv.appendChild(label); }
How this works:
- Selecting elements: We use
document.querySelectorAll(".download_count")to grab all target divs (your original[class^='download_count']selector also works, but this simpler version is better if all divs use exactly thedownload_countclass). - Extracting numbers:
div.textContent.trim()removes extra whitespace around the number, thenparseInt(...)converts the cleaned text to a numeric value. We check!isNaN(count)to skip any divs that don’t contain a valid number. - Tracking the maximum: As we loop through each element, we keep updating our reference to the highest count and the div it belongs to.
- Adding the label: Once we have the div with the highest count, we create a new div element, set its class and text content, then append it to the target div.
Notes:
- If multiple divs share the same highest count, this script will only add the label to the last one it encounters. To add the label to all such divs, modify the loop to collect an array of matching divs instead of storing just one.
- Make sure to run this script after the page has fully loaded—either place it at the end of your HTML body, or wrap it in a
DOMContentLoadedevent listener.
内容的提问来源于stack exchange,提问作者jeys
相关产品推荐
相关产品推荐

