Skip to content

How to use Fetch API and append correctly

This is my html

<!DOCTYPE html>
<html lang="en">
       <div id='data'></div>

This is example html i want to fetch

<html amp="" lang="en">
    <header amp-fx="float-in-top">
        <div class="head-container"></div>
        <div id="lang-list" hidden="" amp-fx="float-in-top"></div>
        <main class="container">
            <article class="post no-sidebar">
                <div class="m-card single-page">.........</div>
            <div class="clear"></div>
        <footer role="contentinfo" class="site-footer no-padding--important">
            <div class="container"></div>

This is code i know how to fetch and append whole html to my id=’data’

const url = ``;
let response = fetch(url);
    .then(response => response.text())
    .then(html => {document.getElementById('data').append(html)});
.catch((err) => console.log("Can’t access " + url + " response. Blocked by browser?" + err));

but i don’t want to append whole html but i only want to get class=”m-card single-page” of and append to my id=’data’. I don’t know how to, please advice me, thanks you


As an approach several things could be used here:

const someHTML = '<main><h1>Some HTML with</h1> <div class="m-card single-page">Lorem dolorem</div></main>';
const parser = new DOMParser();
const parsedHTML = parser.parseFromString(someHTML, "text/html");
const partOfHTMLDOM = parsedHTML.querySelector('.m-card.single-page');
const partOfHTMLDOMString = partOfHTMLDOM.outerHTML;
console.log({parsedHTML, partOfHTMLDOM, partOfHTMLDOMString});