0

How to create child nodes iteratable | Error: removeAttribute() is not a function

example: html:-------------------- <html> <body> <div id="bp"> <a href="1" id="idok" class="ok"> <a href="2" id="idrk" class="rk"> </div> </body> js:--------------------- /* I want to remove class attribute from a tags of bp div. The following code throws error: Uncaught TypeError: removeAttribute is not a function */ var obj=document.getElementById("bp"); mchild=obj.childNodes(); marray=[ ...mchild ]; for (var i=0; i<marray.length; i++) { marray[i].removeAttribute("class"); } /* However the following works - by directly creating array */ marray=[ document.getElementById("idok"), document.getElemenyById("idrk" ]; for (var i=0; i<marray.length; i++) { marray[i].removeAttribute("class"); } https://code.sololearn.com/WCSClkEmYPLG/?ref=app

5th Aug 2021, 5:51 PM
Harshit Jawla
Harshit Jawla - avatar
6 Réponses
+ 2
Harshit Jawla i ran the following code , onload=()=>{ var obj = document.getElementById("bp"); mchild = obj.children; marray = [ ...mchild]; for (var i=0; i<marray.length; i++) { marray[i].removeAttribute("class"); } } Works fine for me.
6th Aug 2021, 4:58 PM
Abhay
Abhay - avatar
+ 2
childNodes is not a function. And childNodes return a node list including text Nodes as well as html elements. If you just want the elements then use children attribute. nodelist is similar to an array but not an array. The following line obviously is wrong then, marray=[... mchild.removeAttribute() ]; It would be , marray=[...mchild] Also you don't need to create a marray since mchild is an array like node list that supports indexing as well. It doesn't supports few array operations , so in that case converting to array should be helpful.
5th Aug 2021, 8:10 PM
Abhay
Abhay - avatar
+ 1
Harshit Jawla children instead of childNodes will give you nodelist of child nodes(excluding text ones)
6th Aug 2021, 3:13 PM
Abhay
Abhay - avatar
+ 1
thanks solved. 😻 Last time I used: marray=new Array(mchild) that caused problem. However both of these two can be used: marray=Array.from(mchild); marray=[ ...mchild ]; Annyways.. a serious thank you for your answer
6th Aug 2021, 5:11 PM
Harshit Jawla
Harshit Jawla - avatar
0
Abhay Thanks. but I appended removeAttribute on the highlighted line by mistake here. I read the same thing that childNodes returns node list which is not pure array, somewhere. But I couldnt find any method/function to get array of child nodes. Help
6th Aug 2021, 1:59 PM
Harshit Jawla
Harshit Jawla - avatar
0
Abhay I tried element.children method but got same error while calling removeAttribute. Uncaught TypeError: mchild[i].removeAttribute is not a function problem is with array creation by childNodes or children method bcz Expected output is given if I manually create array of objects
6th Aug 2021, 4:43 PM
Harshit Jawla
Harshit Jawla - avatar