I am trying to loop through an element (ul list) list and delete all its sub-elements (li elements) which contain a certain special character (colon) but when limiting/focusing forEach() to just a certain list element that I want to work on.
I have tried adding listToWorkOn. just before listElements.forEach( (element) => {...}so I got:
And if I may (because you might be a moderator here of some sort) ā with all niceness and respect to you I suggest to remove the comment about a hit in the head with a nerf bat. I donāt even recall where I found that but anyway I believe that just explaining the mistake would be enough (yes, I know you were kidding, itās a matter of example to those who might not understand it).
If itās any consolation, I found the banter about the nerf bat to have just the right amount of silliness that we expect around here. Right on target, one might say.
Something to keep in mind, in order to use yourVar.forEach() yourVar MUST be an array.
Also, when you chain properties you risk getting an āundefinedā value, especially if a query returns no results ( for example, if your list contained 0 LIs). In your specific case, listToWorkOn doesnt have the property listElements, so thats your error
Finally, the beauty of query selector all is that you can get a COLLECTION of elements via a CSS selector; but this means you must write your selector as specifically as possible, or you risk getting items outside your intended scope. As other people have pointed out you could use a more specific selector with document.querySelectorAll() such as ā.special>liā
Iin case you are actually targeting a specific instance of .special, you can also do: listElements = listToWorkOn.querySelectorAll("li"). Assuming, you donāt have nested list inside your .special. I think this is what you were originally trying to do and I find this handy, when you want to do a .querySelectorAll() dynamically.
Not quite true, as a NodeList (such as is returned by querySelectorAll) implements forEach.
It is true that NodeList is not an Array, but it is an Array-like, so it also qualifies to be put into Array.from() if you need to convert it to an actual array.
Agreed. querySelectorAll is handy to get the elements, and when more than forEach is wanted (such as filter or map, or reduce, thatās where Array.from() makes things nice and easy, by giving easy access to filter/map/reduce methods.
var els = document.querySelectorAll(selector);
var resultingEls = Array.from(els).filter(desiredEls).map(transformEls);