I've been attempting to convert a for loop
into a one-liner using filter()
, but I keep encountering this error:
(index):44 Uncaught TypeError: childrenElements.filter is not a function
.
Functional code snippet:
const parentElement = document.querySelector('.container');
let childrenElements = parentElement.children;
let results = [];
for(i = 0; i < childrenElements.length; i++){
if( childrenElements[i].classList.contains('ui-widget')){
results.push('ui-widget')
}
}
Code snippet that's not working:
const parentElement = document.querySelector('.container');
let childrenElements = parentElement.children;
let results = [];
results = childrenElements.filter(childrenElement => childrenElement.classList.contains('ui-widget'))
I believe the issue stems from childrenElements
not being recognized as an array
, but I'm uncertain about how to address it.
You can view a demonstration here.
UPDATE:
The final code snippet provided by the accepted answer is as follows:
const parentElement = document.querySelector('.container');
let childrenElements = parentElement.children;
let results = [];
results = [...childrenElements].map(childrenElement => childrenElement.classList);
console.log(results)
if (results[0].contains('ui-widget')) {
alert('it has class')
}