getElementsByName returns an element with a wrong name

196 views Asked by At

So in JS I cloned an element and changed all its children names to get their index changed (e.g. 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 when 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 compatibility mode, so according to the docs MSDN - getElementsByName method

Gets a collection of objects based on the value of the NAME or ID attribute.

My question is : Why did the getElementsByName("instanceActeurRole[0].siteId") method return the element named instanceActeurRole[3].siteId ??

ALTERNATIVELY (without the need to see any code)

in which situation would getElementsByName(elemName) return an element which has a different name than the one passed to the method ?

2

There are 2 answers

1
Jacek Pietal On

replace

if(inputElements[j].name.indexOf('instanceActeurRole[0]') == 0) {
    inputElements[j].name = inputElements[j].name.replace("0",nouveauIndex);
}

with

var name = inputElements[j].getAttribute('name');
if (name.indexOf('instanceActeurRole[0]') == 0) {
    inputElements[j].setAttribute('name', name.replace("0", nouveauIndex));
}
1
Jacek Pietal On

YOUR QUESTION Why did the getElementsByName method return the element name instanceActeurRole[3].siteId

omg, you did:

var nouveauIndex = 3;

and then set name to

'instanceActeurRole[0].siteId'.replace('0', nouveauIndex)

what did u expect it to be?! ?! ?! other than instanceActeurRole[3].siteId ?! ?! ?!