Form elements with a name attribute that is the same as the form property, shadow / overrides its own property property. Is there a workaround?

If you have an input element in the form with the same name as the native form property, then this element will be the shadow property native.

For example, consider the following view:

 <form id = "test"> <input name="tagName" type="text" /> <input name="nodeName" type="text" /> </form> 

The form element tagName and nodeName both usually 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"]); 

displayed:

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

The spell is here .

Something even more interesting : in this violin, I just write the form myself. This will usually show you HTML, but now Chrome just TypeError .

+6
source share
2 answers

I cannot think of a way to do this directly in the <form> element. The best I can come up with is to create a clone of the element without any descendants and study the properties of the clone:

 var clonedForm = f.cloneNode(false); console.log(clonedForm.nodeName); 

UPDATE

As noted in the comments, this has the same problem that cloneNode can be redefined in the same way as nodeName . Since any property of the form can be overridden, this makes it difficult to overcome.

+4
source

Edit: I better understand what you want. Each form element has the elements property:

 var f = document.getElementById("test"); f.elements.tagName f.elements.nodeName 

Edit 2: If you want f.tagName to return "FORM" , in this case you cannot. You have overwritten the native property. If you really need to use "tagName" as the name, perhaps you can use parentheses or dot notation:

 HTML: <input type="text" name="element.tagName"> JS: f.elements["element.tagName"] HTML: <input type="text" name="element[tagName]"> JS: f.elements["element[tagName]"] 

Editing 3: Some browsers have a DOM property called localName , which can work if you don’t have a form field inside which has the name "localName".

Basically, do not use your own DOM property names as attribute values ​​for the form field name.

0
source

All Articles