简体   繁体   English

如何从 html 中提取特定元素

[英]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.我正在尝试使用我拥有的功能从 html 中提取一个元素。

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我有一个输入,我在其中放置了页面的 url,该函数为我提供了页面的完整 html

<!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这是它扔给我的 html,现在我想要的是用 offer 类提取那个 div 元素

You can use parseFromString to get the string from the response into a format you can query the DOM.您可以使用parseFromString将响应中的字符串转换为可以查询 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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM