Get HTML div content by ID from string

Advertisements

I am getting data from an API and trying to get the content of a div by the ID ig-tooltip. I am however getting null when trying to print the value. Could someone point me in the right direction please? I came up with this so far:

async function getSkillData(page) {
  try {
    const response = await fetch(`${'https://tarisland.wiki/wiki/api.php?action=parse&format=json&origin=*&page='}${page}`);

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const data = await response.json();
    var doc = new DOMParser().parseFromString(JSON.stringify(data.parse.text), "text/html");

    console.log(doc.getElementById("ig-tooltip"));

    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

getSkillData('Axe_Cyclone');

JSFiddle: https://jsfiddle.net/c71uh4L0/

>Solution :

You’re parsing JSON string instead of actual HTML content from the API response.
data.parse.text['*'] will help you parse the HTML content.

// ...Rest of code
const data = await response.json();
var doc = new DOMParser().parseFromString(data.parse.text['*'], 'text/html');
// ...Rest of code

JSFIDDLE

Leave a ReplyCancel reply