I am trying to extract an element from the html with the function that I have.
document.querySelector('#get_html').addEventListener('click', function () {
var url = document.querySelector('#url_html');
var request = new XMLHttpRequest();
request.open("GET", url.value);
request.send();
request.onload = function() {
console.log(request.response);
};
})
I have an input where I put the url of a page and the function brings me the complete html of the page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div >
<div ></div>
<div ></div>
<div ></div>
<div ></div>
</div>
</body>
</html>
this is the html that it throws me, now what I want is to extract that div element with the offer class
CodePudding user response:
You can use parseFromString
to get the string from the response into a format you can query the DOM.
var responseText = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div >
<div ></div>
<div ></div>
<div ></div>
<div ></div>
</div>
</body>
</html>`;
const parser = new DOMParser();
const doc = parser.parseFromString(responseText, "text/html");
console.log(doc.querySelector(".offer"));