Home > front end >  How to use Fetch API and append correctly
How to use Fetch API and append correctly

Time:12-03

This is my html

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

This is example html i want to fetch

<html amp="" lang="en">
<head>..........</head>
<body>
    <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>
            </article>
            <div class="clear"></div>
        </main>
        <footer role="contentinfo" class="site-footer no-padding--important">
            <div class="container"></div>
        </footer>
        </div>
    </header>
</body>
</html>

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

const url = `https://www.example.com/`;
let response = fetch(url);
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 of example.com and append to my id='data'. I don't know how to, please advice me, thanks you

CodePudding user response:

As an approach several things could be used here:

const someHTML = '<main><h1>Some HTML with</h1> <div >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});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related