DEV Community

Sunil Kumar
Sunil Kumar

Posted on

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

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

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

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?

Top comments (5)

Collapse
 
rhymes profile image
rhymes

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...

Collapse
 
sunilc_ profile image
Sunil Kumar

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

Collapse
 
somedood profile image
Basti Ortiz

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.

Collapse
 
rhymes profile image
rhymes

Nope, since it's a security risk :)

Collapse
 
somedood profile image
Basti Ortiz • Edited

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');
  console.log(inputs);
};

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).