Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Maison012's avatar

Javascript cant count element inside a div element

I am working on a chrome extension, which can sort the videos of a website. For example, I search for a word `stackoverflow' and many videos appear there, but these videos do not have the number of comments displayed in the search result, you have to open this video and get the number of comments. And this is my problem, I actually managed to do something similar, I can get the number of comments but it's not working properly

const property = message.property;
const videos = Array.from(document.querySelectorAll(".video-container")); // Custom class i have added 
const parent = videos[0].parentNode;

originalOrder = Array.from(parent.children); // Store the original order

if (videos.length > 0) {
const openAndPrintVideoContent = async () => {
    for (const video of videos) {
    await new Promise((resolve) => {
        const videoTriggerElement = video.querySelector(".tiktok-18e9va3-DivContainer");
        videoTriggerElement.click(); // Open Video

        // setTimeout(() => {
        const commentCountElement = document.querySelector('[data-e2e="browse-comment-count"]');
        console.log("commentCountElement=>"+commentCountElement.textContent);
        if (commentCountElement && commentCountElement.textContent.trim() !== "") {
            const commentCount = parseFloat(commentCountElement.textContent);
            console.log('CommentCount=>'+commentCount);
            video.dataset.commentCount = commentCount;
        }
        
        // Close video
        const closeButton = document.querySelector('[data-e2e="browse-close"]');
        closeButton.click();

        resolve();
        // }, 2000); 
    });
    }
};

const sortVideosByComments = () => {
    const convertToNumber = (value) => {
    return parseInt(value);
    };

    const sortedVideos = videos.sort((a, b) => {
    const commentCountA = convertToNumber(a.dataset.commentCount);
    const commentCountB = convertToNumber(b.dataset.commentCount);

    console.log("A=>"+commentCountA);
    console.log("B=>"+commentCountB);
    return commentCountB - commentCountA; // Sort by comment count in descending order
    });

    sortedVideos.forEach((video) => {
    const parent = video.parentNode;
    parent.prepend(video);
    });

    console.log("Videos sorted by comments");
};

openAndPrintVideoContent().then(() => {
    console.log("Printing completed");
    sortVideosByComments();
});
} else {
    console.log("No video elements found");
    sendResponse({ success: false, videoCounts: [] });
}

This code returns the number of comments, but it also changes the url in chrome, and then takes me away from the page where I'm sorting, is there any other way I can do what I'm looking for?

0 likes
0 replies

Please or to participate in this conversation.