最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert text to HTML - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 8

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;

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)

发布评论

评论列表(0)

  1. 暂无评论