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

twitter logo ・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");
    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?

twitter logo DISCUSS (5)
markdown 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.

 
 

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

Classic DEV Post from Feb 8

Life Can Be Tough, But We Are DAMN Good at What We Do!

We are problem solvers, thinkers, tinkers, and dreamers. Personal challenges, no matter how severe, can NEVER take that away

Sunil Kumar profile image
A passionate programmer. I love building new things.