2

What I want to achieve Inside React I want to fetch an HTML page with fetch and from the response i get I want to extract some data from a div with a class called "myDiv"

The data I am fetching are in an HTML format. Current I have this code which fetch the data and resolves the response in a text format.

fetch('/my/url')
  .then(response => response && response.text())
  .then(text => console.log('Do something that extract content in class "myDiv"));
RMT
  • 942
  • 2
  • 12
  • 32
  • 1
    Hi, can you please post a snippet of code of the React component you tried to write? So we can start from that to discuss. – Andrea Apr 10 '19 at 09:45
  • You need to provide some snippet you tried, stack is not the platform to ask for solutions but to discuss issues and challenges. – Peter Apr 10 '19 at 09:56

4 Answers4

4

As said above you can use DOMParser

const parser = new DOMParser(),
  dom = parser.parseFromString(text, "text/html");

then access the dom with habitual methods

let myDivContent = dom.querySelector('.myDiv').innerHTML;
Nil
  • 355
  • 1
  • 2
  • 8
  • Thank you very much! I loved that this solution solved all my problems with so few lines. – RMT Apr 12 '19 at 08:25
  • You're welcome, but as in @leaf answer, the us of "const" instead of "let" is more appropriate because theses are static values. – Nil Apr 15 '19 at 09:20
2

You can do something like this, its just plain old Vanila JS.

//This is your fetched html string
let stringHTML = "<div> <h2>Some data</h2><div class='myDiv'> <h1> Test </h1> </div> </div>";
//Create temp element holder
let tempElement = document.createElement("div");
//Add fetched HTML to tempElement
tempElement.innerHTML = stringHTML;

//Now you can query it as it was a normal DOM element
let elementsWithClass = tempElement.getElementsByClassName("myDiv")

document.getElementById('root').appendChild(elementsWithClass[0]);
<div id='root'> 

</div>
SergejV
  • 468
  • 1
  • 8
  • 18
1

Try DOMParser, which parses XML or HTML source code from a string into a DOM Document.

Ex:

const parser = new DOMParser();
const doc = parser.parseFromString(stringContainingHTMLSource, "text/html");
// returns a HTMLDocument, which also is a Document.

const myDiv = doc.querySelector('.myDiv');
console.log(myDiv.innerText);
leaf
  • 1,624
  • 11
  • 16
0

HTML element in string format

var txt = JSON.stringify("<div class='c1'>Welcome</div>")

JSON.parse() convert string to html element ie [object Object]

document.getElementById("demo").innerHTML = JSON.parse(txt)

Mohan
  • 84
  • 5