How do I get all the input tag elements on a web page?

sunilc_ profile image Sunil Kumar ใƒป1 min read

I'm trying to get all input elements present on a webpage with the below code.

document.onload = function() {
    var elements = document.getElementsByTagName("input");

But I see that on some web pages, I don't get the input elements present on the web page. For example on this web page web page -> https://www.wufoo.com/gallery/templates/forms/tuition-reimbursement-form/

What am I doing wrong?


Editor guide

The form is inside an iframe, which is technically a separate page so they are not going to appear in the document. You can access the frames with window.frames.

There's a caveat you might not be able to access those elements in the first place. For example Firefox blocks you because the frame is not from the same origin:

You can find more info about the error here: developer.mozilla.org/en-US/docs/W...


Awesome. Is there a way to go around this error and access the input elements?


Unfortunately, there is none, my friend. However, what you can do is go to the src of the <iframe> and run your original script from there. I ran it myself and I was able to retrieve 28 items.


Nope, since it's a security risk :)


The reason why this doesn't work is because the <input> elements are inside an <iframe> element. To solve your problem, you may need to be clever about it by (recursively) iterating over all <iframe> elements and their contentWindow properties to access the <input> elements you are looking for.

If you want to keep things simple, you can also just change your onload handler as such:

document.onload = function() {
  const iframe = document.getElementsByClassName('wufoo-form-container')[0];
  const documentInsideTheIframe = iframe.contentWindow.document;
  const inputs = documentInsideTheIframe.getElementsByTagName('input');

However, this comes with another problem. The site disables cross-origin access to <iframe> elements for security reasons (which is a very good thing). The main website has a domain of www.wufoo.com while the <iframe> containing the <input> elements comes from the domain gallery.wufoo.com. Since the two domains are not the same, any access to the DOM of the <iframe> is not allowed.

In other words, what you're asking for is impossible because the site is pretty secure (which, again, is a very good thing).