javascript - 获取 Javascript 结果的确切内部文本
问题描述
我在一个网站上运行这个脚本:
document.forms[0].getElementsByTagName('input')[2]
它的输出是:
<input _ngcontent-aui-c140="" pinputtext="" type="password" formcontrolname="password" autocomplete="current-password" class="ng-untouched ng-pristine ng-invalid p-inputtext p-component">
这正是我需要的(或逗号分隔的东西)。当我尝试将其转换为字符串 uaingJSON.stringify
时,它会TypeError: Converting circular structure to JSON
出错。没问题,我也可以借助这个把循环结构转换成字符串:Chrome sendrequest error: TypeError: Converting circular structure to JSON
但它会返回很多额外的未知字符串!我只需要逗号分隔格式 (JSON) 的内部 HTML。我应该怎么办?
解决方案
您可以使用outerHTML
获取元素及其后代的 HTML:
const input = document.forms[0].getElementsByTagName('input')[2];
console.log(input.outerHTML);
<form>
<input>
<input>
<input _ngcontent-aui-c140="" pinputtext="" type="password" formcontrolname="password" autocomplete="current-password" class="ng-untouched ng-pristine ng-invalid p-inputtext p-component">
</form>
我只需要逗号分隔格式 (JSON) 的内部 HTML。我应该怎么办?
如果您的意思是要对表单中的所有input
s 进行上述操作,则可以循环遍历结果getElementsByTagName
并获取outerHTML
每个结果,然后将字符串与 连接在一起join(",")
。(虽然我可能不会为此使用 CSV。)
const inputs = document.forms[0].getElementsByTagName('input');
const strings = Array.prototype.map.call(
inputs,
input => input.outerHTML
);
console.log("Joined with a comma:");
console.log(strings.join(","));
console.log("As JSON:");
console.log(JSON.stringify(strings));
<form>
<input type="text" class="example">
<input type="date" class="blah">
<input _ngcontent-aui-c140="" pinputtext="" type="password" formcontrolname="password" autocomplete="current-password" class="ng-untouched ng-pristine ng-invalid p-inputtext p-component">
</form>
推荐阅读
- c++ - C++ 十进制到十六进制(字符串下标超出范围)
- ionic3 - 如何识别我是否属于 IONIC 3 中当前经纬度的指定半径?
- c# - 仅从给定字符串获取参数名称
- android - 单击“下一步”按钮时如何在水平回收器视图中显示下一个项目?
- amazon-web-services - AWS Amplify - 禁用当前用户账户
- python - 我想使用opencv删除边界
- django - PyCharm + Python 3.6 + Django + 调试 + 生成器 == 痛苦的世界
- r - 成对操作 data.frame 中的行
- java - install4j 7.0.6:从“语言代码替换脚本”取消安装
- python - Opencv Python用一个常数调整大小