Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can i extract a specific element from the html

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading