Home > Back-end >  Change text Inside heading with info from Array
Change text Inside heading with info from Array

Time:09-27

I'm making a fetch call to retrieve some data on player cards. I'm trying to display said cards and running into issues accurately parsing JSON and showing info in HTML.

Here is an example HTML heading for a card:

<h3 class="card__title"><a href="item.html">Example Card</a></h3>

Here is some JavaScript code I used after the fetch call:

let cardList = json.results         
let cardTitle0 = cardList[0].name.toString();

How do I change the text from Example Card -> cardTitle0 from my array? This question applies to other attributes from the array and HTML objects.

CodePudding user response:

You'll need to use the h3 element to get the link:

const link = document.querySelector(".card__title a");

// These can be const.
const cardList = json.results         
const cardTitle0 = cardList[0].name.toString();

link.innerHTML = cardTitle0;

For multiple cards, you'd have to loop through the cardList json result and also through the elements on the page.

This is just an idea off the top of my head so I can't verify this code works or is even the best option for addressing multiple cards but hopefully it'll get you going in the right direction.

const links = document.querySelectorAll(".card__title a");

const cardList = json.results;

// Loop through the links on the page.
for (let i = 0; i < links.length - 1; i  )
{
    for (let j = 0; j < cardList.length - 1; j  )
    {
        const title = cardList[j].name.toString();

        links[i].innerHTML = title;
    }
}
  • Related