-1

I run this script on a website:

document.forms[0].getElementsByTagName('input')[2]

it's output is:

<input _ngcontent-aui-c140="" pinputtext="" type="password" formcontrolname="password" autocomplete="current-password" class="ng-untouched ng-pristine ng-invalid p-inputtext p-component">

It is what I exactly need (or something comma separated). when I try to convert it into a string uaing JSON.stringify, it gives a TypeError: Converting circular structure to JSON error. No problem, I can also convert the circular structure into a string with the help of this: Chrome sendrequest error: TypeError: Converting circular structure to JSON

But it will return so many extra unknown strings! I just only need that inner HTML in a comma-separated format (JSON). what should I do?

Inside Man
  • 4,194
  • 12
  • 59
  • 119

1 Answers1

1

You can use outerHTML to get the HTML for the element and its descendants:

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>

I just only need that inner HTML in a comma-separated format (JSON). what should I do?

If you mean you want the above for all of the inputs in the form, you can loop through the result from getElementsByTagName and get the outerHTML of each of them, and join the strings together with join(","). (Though I probably wouldn't use CSV for this.)

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>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875