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"));
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"));
Share
Improve this question
asked Apr 10, 2019 at 9:30
RMTRMT
1,1623 gold badges17 silver badges34 bronze badges
2
- 1 Hi, can you please post a snippet of code of the React ponent you tried to write? So we can start from that to discuss. – Andrea Commented Apr 10, 2019 at 9:45
- You need to provide some snippet you tried, stack is not the platform to ask for solutions but to discuss issues and challenges. – Manu Commented Apr 10, 2019 at 9:56
4 Answers
Reset to default 8As 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;
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>
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);
HTML element in string format
var txt = JSON.stringify("<div class='c1'>Wele</div>")
JSON.parse() convert string to html element ie [object Object]
document.getElementById("demo").innerHTML = JSON.parse(txt)