首页 > 解决方案 > 获取 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。我应该怎么办?

标签: javascript

解决方案


您可以使用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。我应该怎么办?

如果您的意思是要对表单中的所有inputs 进行上述操作,则可以循环遍历结果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>


推荐阅读