Why do I remove the subclass and change the length of the arr I got before?
problem description
this function first takes an array of classes, saves it, and then removes child elements through the parent element, but why does the array length change during removal?
the environmental background of the problems and what methods you have tried
I debugged it on the console, and the sentence that got the array was executed only once.
related codes
/ / Please paste the code text below (do not replace the code with pictures)
function removeClassEle (cls) {
var arr = document.getElementsByClassName(cls);
var c=arr.length;
var parents = arr[0].parentNode;
for(var i = 0; i<c; iPP){
parents.removeChild(arr[0]); //arrarr
}
console.log(arr.length) // 1, 0
}
what result do you expect? What is the error message actually seen?
Please give me a hint
you need to supplement the knowledge passed by values and references
for basic data types, the = of Javascript is passed
for objects, the = of Javascript is a reference
There are many articles on
sf: https://codeshelper.com/sear...
can take a look at this: https://codeshelper.com/a/11...
var x = 123;
var y = x;
x = 1024;
console.log(y); // 123
var a = [1, 2, 3];
var b = a;
a.pop();
console.log(b);// [ 1 , 2 ]
var a = {myProperty:1024};
var b = a;
a.myProperty = 123;
console.log(b); // { myProperty: 123 }
simply because var parents = arr [0] .parentNode; the parents here is a reference, corresponding to an address in memory, and the parents will change when the value in it changes.
getElementsByClassName
returns HTMLCollection type, which is a class array. HTMLCollection
has its own characteristics:
The HTMLCollection in
HTML DOM is live; it updates automatically when the structure of the document it contains changes.
when you convert a class array to an array, the length does not change:
function removeClassEle(cls){
var arr = document.getElementsByClassName(cls);
var c=arr.length;
var parents = arr[0].parentNode;
arr = [].slice.call(arr) //
for(var i = 0; i<c; iPP){
parents.removeChild(arr[i]); // arr[i]
}
console.log(arr.length) // arr.length
}
but this is not recommended, because the dom element has been removed, but dom is also referenced by arr, so dom will not be removed from memory, and may cause memory leaks.