简体   繁体   中英

getElementsByName returns an element with a wrong name

So in JS I cloned an element and changed all its children name s to get their index changed (eg 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 ?

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));
}

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 ?! ?! ?!

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