Cannot use ‘insertAdjacentHTML’ inside a JSON fetch

So I’m creating this script that goes trough a list of ahref links,

  • checks if they’re a github.com link,
  • fetches a JSON file based on that github link,
  • and prepends a <strong>2024-10-20</strong> element with the date key from this JSON file.

The problem is, if I console.log(jsonResponse.date) the JSON response, inside of this fetch, the date appears to be outputted, as a string.
But when I try to use it on a insertAdjacentHTML I get an error.

TypeError: Cannot read properties of undefined (reading ‘insertAdjacentHTML’)
at getSuggestions (scripts.js:78:17)

Which points to this line: gitLinks[i].insertAdjacentHTML


Here is my code:

HTML:

<div class="page-content">
    <ul>
        <li><a href="//github.com/NoahY/q2a-badges">Badges Plugin</a>. Provides user badges which recognize users' activities and achievements.</li>
        <li><a href="//github.com/amiyasahu/q2a-breadcrumbs">Breadcrumbs Widget</a>. Displays navigational breadcrumbs showing the path to the currently viewed page.</li>
        <li><a href="//github.com/arjunsuresh/q2a-betterpoints">Better Points</a>. Extends the default point system by adding points for giving comments, receiving comment upvotes/downvotes.</li>
    </ul>
</div>

JS:

const gitLinks = document.querySelectorAll('.page-content li a[href*="https://github.com/"]');

let jsonDates = [];

for(var i=0; i<gitLinks.length; i++) {
    const getGithubHref = gitLinks[i].getAttribute('href');

    const githubDomain = 'https://github.com/';
    const githubRepository = getGithubHref.slice(getGithubHref.indexOf(githubDomain) + githubDomain.length);
    const githubJSON = 'https://raw.githubusercontent.com/' + githubRepository + '/master/metadata.json';
    
    const getDates = async () => {
        try {
            const response = await fetch('https://raw.githubusercontent.com/amiyasahu/q2a-breadcrumbs/master/metadata.json');
            if(response.ok){
                let jsonResponse = await response.json();
                console.log(jsonResponse.date);
                
                gitLinks[i].insertAdjacentHTML(
                    'beforebegin',
                    `<strong>${jsonResponse.date}</strong>`,
                );
                
                jsonDates.push(jsonResponse.date);
            }
        }
        catch(error) {
            console.log(error);
        }
    }
    getDates();
}

console.log(jsonDates);

  • I’ve also tried to push the responses to and empty array jsonDates, but it doesn’t work either. The array returns empty.
  • If I move the gitLinks[i].insertAdjacentHTML outside the fetch, it prepends normally.
    I can’t figure out what the problem is.