If you have an input
element in a form with the same name as a form's native property, then that element will shadow the native property.
For example, consider the following form:
<form id = "test">
<input name="tagName" type="text" />
<input name="nodeName" type="text" />
</form>
The form
element's tagName
and nodeName
both normally return FORM
. But in this case, the following code:
var f = document.getElementById("test");
console.log(f.tagName);
console.log(f.nodeName);
console.log(f["tagName"]);
console.log(f["nodeName"]);
displays:
<input name="tagName" type="text">
<input name="nodeName" type="text">
<input name="tagName" type="text">
<input name="nodeName" type="text">
Is there a workaround for this (other than renaming the fields)? getAttribute
works for things like name
, action
, or method
, but not for properties like nodeName
or tagName
.
Fiddle here.
Something even more interesting: in this fiddle I'm simply logging the form itself. Normally that would show you the HTML, but now Chrome simply logs TypeError
.
If something is a form, use a form element. This helps assistive devices like screen readers better understand the content of the page and give the person using them more meaningful information.
elements. The HTMLFormElement property elements returns an HTMLFormControlsCollection listing all the form controls contained in the <form> element. Independently, you can obtain just the number of form controls using the length property.
I can't think of a way of doing it directly on the <form>
element. The best I can think of is creating a clone of the element without any descendants and examining the clone's properties:
var clonedForm = f.cloneNode(false);
console.log(clonedForm.nodeName);
UPDATE
As pointed out in the comments, this has the same problem in that cloneNode
can be overridden in the same way as nodeName
. Since any property of the form can be overridden, this makes it a difficult problem to overcome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With