Exploring the possibility of converting a for loop into a one-liner filter method in JavaScript

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

Answer №1

To convert your HTMLCollection object into an array, you can utilize the spread operator to make your data iterable:

convertedArray = [...childrenElements].filter(child => child.classList );

If you are specifically looking for a particular class within the elements, you should map over the elements to create an array of classList arrays and then use the contains method to search for the desired element.

classListArray = [...childrenElements].map(child => child.classList );

if (classListArray[0].contains('ui-widget')) {
    alert('The class is present');
}

Answer №2

One reason for this is because childrenElements represents an HTMLCollection which allows access to objects using indexes like childrenElements[0].

However, it lacks the same methods as an Array object. To overcome this, you can convert it to an Array using:

Array.from(childrenElements)

Once converted, you have access to all the Array methods.

Keep in mind that converting a large list might not be the most efficient method, as it involves converting the HTMLCollection to an Array and then looping over it again to filter elements.

Answer №3

If your code has childrenElements stored as an HTMLCollection, which is similar to an array but not exactly the same, you simply need to convert it into an array for proper functionality.

const parentElement = document.querySelector('.container');

let childrenElements = parentElement.children;
console.log(childrenElements)
let results = [];

// working code snippet - uncomment to test it
/* for(i = 0; i < childrenElements.length; i++){
  if( childrenElements[i].classList.contains('ui-widget')){
    results.push('ui-widget')
  }
}  

console.log(results) */

// not working code snippet
results = Array.from(childrenElements).filter(childrenElement => childrenElement.classList )

console.log(results)

if (results[0] === 'ui-widget') {
alert('it has class')
}
<div class="container">
  
  <div class="ui-widget ui-widget-content widget-left">
    I am a ui-widget
  </div>
  <p class="paragraph">
  Hello Paragraph
  </p>
  <button class="btn">
   Close
  </button>
</div>

Answer №4

Transform the data into an array by utilizing this method

let convertedArray = Array.from(childrenElements);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to retrieve the initial <ul> element from a JavaScript document?

Just to clarify, I'm looking to target a specific div with a class and the first <ul> from a document (specifically in blogger). Currently, I have a JavaScript function that grabs the first image and generates a thumbnail as shown below: //< ...

Scaling texture to fit on a plane in THREE.js

I am attempting to 'fit-to-scale' a mapped image texture on a single plane, aiming to simulate the behavior of object-fit:cover. The image map needs to scale proportionally in order to cover the entire plane completely. I have experimented with ...

Discover the two specific values within an array that a given element is affiliated with

Imagine I have an array that looks like this: $months = Array('3','6','12','15','18','21','24'); Now, let's say I have a variable called $n with a value of 5. What would be a suit ...

How can I retrieve a Jquery tooltip from a HiddenField?

I am trying to utilize a hidden field in my asp.net calendar to display a message using JQ Tooltip. However, when I attempt to use the value of the HiddenField for the tooltip, I encounter an error. $("#hf_taskID_cal").tooltip($("#hf_taskID_cal").val()); ...

The alert is not displaying when making an Ajax POST request

Here is the code I'm using to delete a comment. However, after deleting the comment, I am not getting any alert for success. Can someone help me identify the issue? function DeleteComment(id) { jQuery.ajax({ url: "/Admin/Comment/ ...

Error occurs when running Visual Studio Code locally - variable not defined

After successfully going through a Microsoft online demo on setting up an httpTrigger in Visual Studio Code with JavaScript to upload it to Azure Functions, I decided to customize the code for a specific calculation. I managed to get the calculation done a ...

Using jQuery and JavaScript: The recursive setTimeout function I created accelerates when the tab is no longer active

I am facing a unique challenge with my jQuery slideshow plugin that I'm currently developing. Although the code is running smoothly, I have observed an issue where if I leave the site open in a tab and browse elsewhere, upon returning to the site (us ...

A guide on displaying multi-dimensional arrays and single-dimensional arrays together using a for loop

I have a coding challenge where I need to output a specific set of hobbies for each day of the week. The desired result is as follows: My hobbies on Mondays are Poker, VideoGames My hobbies on Tuesday are Board Games, Hiking, Rockclimbing My hobbies on ...

What is the best way to delete a parent table row in React JS when the child "delete" button is clicked?

Struggling with hiding a table row in my React JS app upon clicking the "delete" button. The functions causing issues are: ... changeHandler: function(e) { ... }, deleteHandler: function(e) { e.currentTarget.closest("tr").style.visibility = "hidden"; } ...

What is the best way to remove an element within another element using Jquery?

$(document).ready(function() { $("#movieForm").submit(function(e) { e.preventDefault(); var wordToSearch = $("#movieInput").val(); $.ajax({ url: 'http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey=x78wnu3hc3ve7amqef ...

Getting the location of a mouse click and adding tags (marks) on an image: a simple guide

Is there a way to incorporate images with tagged marks similar to Facebook's image tagging feature? How can I retrieve the X and Y coordinates of tags on the image itself (not the screen) and display them in a responsive manner? ...

Struggling with dragging Vue.js modals?

I am currently utilizing the vue-js-modal library, and I'm encountering an issue with it. Whenever I set my modal to be draggable by using :draggable="true", I can drag it around but then I am unable to input any text in the form fields. It seems to c ...

Using dynamic template URLs in resolving with Angular's UI-Router can provide flexibility

Currently, I have implemented a parent directive for an entire view to interchange templates based on the outcome of a promise. .directive('myDirective', function(myService) { var rootDir = '/path/to/templates'; return { ...

What is the best way to convert this code snippet into an asynchronous operation using promises?

Any Glue. Please do not provide an example involving SETTIMEOUT. My manager mentioned that it is unnecessary to have more than one then() statement if the then()'s do not return any new promises. I couldn't fully grasp the concept, even though I ...

Display the option to "Delete" the link only when there are multiple images in my image collection

I am using jQuery and Ajax to remove banner images from my website. However, I want to make sure that if there is only one image left, it cannot be deleted. Each image in the list has a corresponding delete link: echo '<a class="delete j_bannerd ...

Building HTML within an Angular JS Directive

I am in the process of creating a custom directive for a basic modal window, which will be used like this: <modal content="<div class='error-text'>this is the content</div>"></modal> This should result in the following H ...

Utilizing Packery.js in AngularJS

Having some trouble trying to integrate Packery.js with my angularjs app. It seems like they are not working well together. I tried setting isInitLayout to false, but no luck. This is the (bootstrap 3) HTML code I am using: <div class="row" class="js ...

Changes in menu layout in response to window resizing

The menu needs to be centered on the website and adjust to the browser window resizing. Currently, it's positioned in the center and the animation is working fine. However, when I attempt to make the menu responsive so that it stays centered when resi ...

Exploring the capabilities of Angular functions through JavaScript and jQuery

As a coding novice, I'm unsure which language this is. The component.ts file I have contains a function that I need to access outside of ngOnInit(). I tried using this.openDialog(), but it came up as undefined. I attempted defining the function in Ja ...

Merging two separate arrays together

Currently working on a simple genetic algorithm involving uniform crossover operation. I am using two arrays as parents and mothers to concatenate the child's offspring. Encountering an issue with adding the arrays together. Any assistance would be gr ...