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 class="offer">
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></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
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 class="offer"> <div class="card"></div> <div class="card"></div> <div class="card"></div> <div class="card"></div> </div> </body> </html>`; const parser = new DOMParser(); const doc = parser.parseFromString(responseText, "text/html"); console.log(doc.querySelector(".offer"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.