2

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

1

1 Answer 1

2

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"));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.