Loop through an array of elements in JavaScript and retrieve the element with the largest pixel size

I am facing a challenge with elements positioned absolutely on a web page.

My goal is to iterate over these elements and identify the one with the highest top value.

I attempted two different approaches:

const elems = document.querySelectorAll('.index-posts > li');

const newElems1 = [...elems].filter(item => Math.max(parseInt(item?.style?.top))); 
const newElems2 = Math.max([...elems].map(item => parseInt(item?.style?.top?.split('px')[0])); 

I believe the first method should work, but I may not be implementing Math.max correctly. It seems this approach returns all items because it's calculating the max height for each item.

I came across a helpful post on Stack Overflow that inspired my second variable creation: Finding the max value of a property in an array of objects

const elems = document.querySelectorAll('.index-posts > li');

// const newElems = [...elems].filter(item => Math.max(parseInt(item?.style?.top)));

const newElems = Math.max([...elems].map(item => parseInt(item.style.top.split('px')[0]));

console.log(newElems);
<ul class="index-posts row"><li id="affirmation" style="top: 3px; left: 0%;">
            // Some content here
        </li><li id="effort" style="top: 261px;">
            // More content here
        </li><li id="gods_and_monsters" style="top: 693px; left: 64%;">
            // Additional content here
        </li>
        /* more list items */
</ul>

If you can provide guidance on how to solve this issue, I would greatly appreciate it.

Answer №1

If you want to determine the item with the highest top value, you can utilize the reduce method on the array. This method allows you to iterate over each item in the array and compare their top values to find the one with the largest one.

const maxTopItem = Array.from(elements).reduce((prevItem, currentItem) => {
    return parseInt(currentItem.style.top) > parseInt(prevItem.style.top) ? currentItem : prevItem;
});

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

Implementing coordinate formatting in JavaScript [Node.js]

I'm looking to tweak the JSON output into this specific format: [ 50.87758, 5.78092 ], [ 52.87758, 5.48091 ] and so on. Currently, the output looks like this: [ { lat: 53.1799, lon: 6.98565 }, { lat: 52.02554, lon: 5.82181 }, { lat: 51.87335, l ...

What is the best way to add user login information to the request pipeline in Express.js?

In my current project, I've been working on a middleware that is responsible for extracting the user model and attaching it to the request pipeline. Although I have successfully implemented a token extractor middleware that attaches the token to the r ...

Swapping out nodes for images using d3.js

Below is the code snippet I am currently executing http://jsfiddle.net/a7as6/14/ I have implemented the following code to convert a node to an image: node.append("svg:image") .attr("class", "circle") .attr("xlink:href", "https://github.com/favico ...

Check the length of a ngRepeat array after the initial filtering before applying limitTo for further refinement

Currently, I am implementing pagination in my Angular application by using a custom startAtIndex filter along with the limitTo filter. My goal is to show the total number of results in the dataset, regardless of the current page. However, due to the use of ...

Stop files from being downloaded every time the page is visited

Within my Vue.js application, there is an animation that appears on a specific page. However, each time I visit that page, the assets for the animation are re-downloaded from scratch. Although the app does get destroyed when leaving the page, using v-show ...

Separating stylesheets, head, and other elements in a curl response

After successfully using curl to retrieve an external site, I noticed that the results were interfering with my own content. The CSS from the external site was affecting my webpage's layout and z-index values were conflicting. I am seeking a solution ...

Implementing JSON methods in C# WebService to enable communication with external servers

Is it possible to integrate an asp.net web service written in C# into an HTML5/JavaScript website? The challenge is that the web service and client are located on different domains, requiring a cross-domain request. ...

Tips for altering the color of string outputs

Can you help me modify a function to display different colors based on the output? For instance, I want it to show in orange if the result is too low, and in red if it indicates obesity. bmiCalculation() { var weight = parseInt(this.currentWeight); ...

What are the best ways to incorporate mistakes into my JavaScript mortgage calculator?

I am struggling to set up my calculator so that it triggers an error message if the APR goes over 25% or falls below 0. Also, the Loan Term should be greater than 0 and less than or equal to 40, otherwise display an error message. I have attempted differen ...

Problem with Raphael Sketch and Request to Ajax

Utilizing Raphael.js and jQuery Ajax, I am attempting to display some dots (circles) on the map in this [Demo][1]. I have a PHP file called econo.php which looks like this: <?PHP include 'conconfig.php'; $con = new mysqli(DB_HOST,DB_USER,DB_P ...

Changing Three.js from mouse interaction to a random movement pattern

Recently, I came across this interesting website with a background that lights up depending on the movement of your mouse. I was wondering if there is a way to make that illuminated spot move around on its own. If you want to see how it looks, check out th ...

pattern validation using a regular expression

I am just starting to learn about regular expressions. In my current project, I am allowing users to input amounts in both shorthand and full digit formats using a material UI TextField component. Here are some examples of the input formats: 400k - short ...

How can we determine if the return value from Object.values is an array or not, since it returns a JavaScript array without the brackets?

In my programming code, I work with two separate JSON files. I iterate through each item in the first file and compare its values with those in the second file. Based on the comparison results, I generate a third JSON file which essentially merges the cont ...

Deleting an added element upon closing the dialog box

Utilizing JQuery and Ajax, I successfully update my database. Following each update, a png icon is displayed briefly for 1 second. Specifically, the update form is contained within a JQuery dialog box. However, upon closing the dialog box after an update, ...

What steps do I need to take in Bootstrap 5 to add a search icon to the navbar that reveals a search box beneath it when clicked?

I've made progress on the navbar design Now, I'm looking to add a search icon next to the login button. Clicking on the search icon should reveal a search box below the navbar, similar to the image shown below. My transparent navbar has a relati ...

Displaying a group of elements in ReactJS

I'm currently working on assembling an array using different JSX components. There's a function I've created that populates this array with components and then returns it. let components = []; switch (obj.type) { case 'title': ...

Optimizing Angular.js templates for faster loading using Node.js pre-compilation

As I delve into learning Angular and integrating it with my current Node.js framework, I find myself facing some challenges. Previously, I utilized Handlebars.js as my templating engine in Node.js, where I would build the context on the server side and the ...

Making a Cross-Origin Resource Sharing (CORS) request with jQuery utilizing the $

I am currently in the process of building a web application that relies heavily on data from multiple domains. Approximately 90% of the requests made by my application are cross-domain requests. However, I have encountered an issue where I am unable to re ...

Create a dynamic JavaScript animation with frames

Is there a simpler method to animate a sprite with just 4 frames in HTML Canvas? Having a background in AS3 and C#, I found the code below to be overly complicated. It seems like I'll be spending hours trying to decipher it. Is there a more modern or ...

Discovering hidden Mixed Content problems on a secured website can be a challenging task

After deploying a simple PWA application on the NGINX server, which was created using Vue CLI, I decided to use hash mode instead of history mode for the Vue router. Even though the website is secure: I am encountering the following errors and I'm n ...