GetElementsByName returns an element with an invalid name
So, in JS, I cloned an element and changed all of its children name
to change their index (like instanceActeurRole[0].siteId
becomes instanceActeurRole[3].siteId
)
...
<table>
<tbody id="rolesdiv_xxxx">
<input type="hidden" name="instanceActeurRole[0].siteId" value="920501">
</table>
...
var originalRolesDiv = document.getElementById("rolesdiv_xxxx");
var tableRoles = originalRolesDiv.parentNode;
var cloneRolesDiv = originalRolesDiv.cloneNode(true);
var inputElements = cloneRolesDiv.getElementsByTagName("input");
var nouveauIndex = 3;
for(var j = 0 ; j < inputElements.length ; j++){
if(inputElements[j].name.indexOf('instanceActeurRole[0]') == 0) {
inputElements[j].name = inputElements[j].name.replace("0",nouveauIndex);
}
}
tableRoles.appendChild(cloneRolesDiv);
Now that I do
>>document.getElementsByName("instanceActeurRole[0].siteId").length
2
>>document.getElementsByName("instanceActeurRole[0].siteId")[1].name
"instanceActeurRole[3].siteId"
>>document.getElementsByName("instanceActeurRole[0].siteId")[1].getAttribute('name')
"instanceActeurRole[3].siteId"
>>document.getElementsByName("instanceActeurRole[0].siteId").length
2
>>document.getElementsByName("instanceActeurRole[0].siteId")[0].name
"instanceActeurRole[0].siteId"
>>document.getElementsByName("instanceActeurRole[0].siteId")[0].id
""
>>document.getElementsByName("instanceActeurRole[0].siteId")[1].name
"instanceActeurRole[3].siteId"
>>document.getElementsByName("instanceActeurRole[0].siteId")[1].id
""
I am working on IE8 in quirks mode, so according to the MSDN docs - getElementsByName method
Gets a collection of objects based on the value of the NAME or ID attribute.
My question is: Why does the method getElementsByName("instanceActeurRole[0].siteId")
return an element named instanceActeurRole[3].siteId
?
ALTERNATIVELY (no need to see the code)
in what situation is getElementsByName(elemName)
returning an element that has a different name than the one passed to the method?
source to share
replace
if(inputElements[j].name.indexOf('instanceActeurRole[0]') == 0) {
inputElements[j].name = inputElements[j].name.replace("0",nouveauIndex);
}
from
var name = inputElements[j].getAttribute('name');
if (name.indexOf('instanceActeurRole[0]') == 0) {
inputElements[j].setAttribute('name', name.replace("0", nouveauIndex));
}
source to share
YOUR QUESTION Why does getElementsByName method return element name instanceActeurRole [3] .siteId
omg, you did:
var nouveauIndex = 3;
and then give the name
'instanceActeurRole[0].siteId'.replace('0', nouveauIndex)
what did you expect this?!?!?! except for an instance of ActeurRole [3] .siteId?!?!?!
source to share