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 class=”m-card single-page” of example.com and append to my id=’data’. I don’t know how to, please advice me, thanks you
Advertisement
Answer
As an approach several things could be used here:
- DOMParser https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
- querySelector (to get some DOM element by selector) https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelector
- outerHTML (to get HTML string from a DOM element you need) https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML Please check the example with the part which getting some parts from HTML string (https://codepen.io/alekskorovin/pen/gOGpBVL):
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});