简体   繁体   English

如何使用JavaScript从外部网页定位HTML DOM元素

[英]How to target HTML DOM elements from an external webpage using JavaScript

I have obtained the whole HTML of the webpage am getting repeated errors like response.getElementById is not a function 我已经获得了网页的整个HTML,并且遇到了诸如response.getElementById is not a function重复错误。

this is my code: 这是我的代码:

$.get('myUrl', function(response) {
  storageVariable = response.getElementById('#id').textContent;
  console.log(storageVariable);
})

What I exactly want to do is target the different elements of the external webpage, and store them in different variables. 我真正想做的是针对外部网页的不同元素,并将它们存储在不同的变量中。

Any help is greatly appreciated! 任何帮助是极大的赞赏!

If you got the HTML as a String from an AJAX call, for example, you can use the DOMParser API and then use all document methods on this object: 例如,如果从AJAX调用获得HTML作为字符串,则可以使用DOMParser API,然后对该对象使用所有document方法:

$.get('myUrl', function(response) {
  let parser = new DOMParser();
  let parsedHtml = parser.parseFromString(response, 'text/html');
  console.log(parsedHtml.getElementById("<something>").innerHTML);
})

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

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