简体   繁体   中英

Why doesn't document.getElementById(“thediv”).forms[0] return any elements?

Why does document.forms[0] return something (the first form on the page), but document.getElementById("thediv").forms[0] does not return anything?

Example JSFiddle

On a more complex page, I would expect the be able to narrow down the scope of the browser's search for form elements by specifying an ID.

forms is a property of document . document.getElementById is a function that returns an HTMLElement object. This does not have a property called forms. Look at jQuery if you'd like more logical javascript.

Because there isn't such a property forms on DOM element objects, only the document object .

Forms are still forms within the same page no matter where they're found in the document tree. If you need to grab a subset of forms on a page based on a certain parent element, you'll probably want to try a library like jQuery.

document.getElementById('thediv').getElementsByTagName('form')[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM