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

How do I navigate to the homepage in React?

I am facing an issue with my routes. When I try to access a specific URL like http://localhost:3000/examp1, I want to redirect back to the HomePage. However, whenever I type in something like http://localhost:3000/***, I reach the page but nothing is dis ...

Bluebird refuses to execute the then() function, despite the code that was functional before

I am in the process of constructing a node framework for my upcoming projects, with a focus on easy management. The framework already includes a configuration module. Recently, I implemented an error handler and made updates to the Config module to incorp ...

Changing ch to Px in CSS

Important Notes: I have exhaustively explored all the questions and answers related to this particular topic. The question I have is very straightforward: How many pixels are equivalent to 1 character? Here's a sample of my code - code Related Sear ...

A dynamic context menu using jQuery within AJAX-loaded content

After spending hours searching for a solution without success, I am turning to this forum for help (I have come across similar questions but none of them have solved my issue). The problem I am facing is with implementing a custom context menu on a page t ...

Having trouble getting sweet alert to work with my PHP script

I’m integrating Sweet Alerts 2 into my webpage in order to prompt the user when trying to delete something. However, I'm encountering an issue where the PHP file is not being triggered when the user presses delete and the Sweet Alert does not appear ...

When the mouse hovers over DIV2, the background image of DIV1 will be replaced

I have a full-screen background div with the ID #background-change. Within that full-screen background, I have 3 Divs named .fullscreen-column-1, .fullscreen-column-2, etc. My goal is to change the background image of #background-change when the mouseove ...

Issue with ExpressJS Regex not correctly matching a path

I'm currently struggling with a simple regex that is supposed to match words consisting of letters (0-5) only, but for some reason it's not working as expected. Can anyone help me figure out the correct expression and how to implement it in Expre ...

Issue with styled-components not being exported

Issue: ./src/card.js There was an import error: 'Bottom' is not exported from './styles/cards.style'. card.js import React from 'react' import { Bottom, Color, Text, Image } from "./styles/cards.style"; fu ...

Sharing Iframes across various Components within a Single Page Application (like Youtube)

Did you know that Youtube now lets you minimize the player while browsing the site? It's similar to the functionality on LolEsports.com with Twitch and embedded Youtube players. I'm interested in adding this feature to my own website. Here' ...

Tips for utilizing SSR data fetching in Next.js with Apollo Client

Trying to integrate the apollo-client with Next.js, I aim to fetch data within the getServerSideProps method. Let's consider having 2 components and one page- section.tsx represents component-1 const Section = () => { return ( <div& ...

When integrating string variables into JavaScript regular expressions in Qualtrics, they seem to mysteriously vanish

I have been working on a project to analyze survey responses in Qualtrics by counting the number of matches to specific regular expressions. For example, whenever phrases like "I think...", "In my opinion," are used, the count increases by one. Below is t ...

Unraveling the Mystery of Passing Props in React.js

Currently taking an online course to learn React, I encountered a unique scenario where one property is attached to another property in this manner: this.props.property01(this.props.property02) The tutor briefly touched on this code line, leaving me quit ...

Verify whether an option is chosen in CakePHP 3 form

I'm working on a form where users can select Types and each type has an associated color. In my TypesController, I have a function that retrieves the list of types with their IDs, names, and colors. $types = $this->Types->find('list') ...

Navigating external pages with Vue Router

Could really use some assistance. I've got a JSON file filled with various URL links, some internal and some external. This is what the JSON structure looks like: [ {stuff..., "Url":"https://www.google.com/", stuff..}, {stuff... ...

The content inside the bootstrap modal is not visible

My goal is to trigger a modal window when a specific div is clicked using bootstrap modal. However, upon clicking the div, the screen darkens but the modal body fails to appear. Code: <html> <head> <title></title> ...

As soon as I closed the modal, I noticed that the checked inputs reverted back to

I am using checkboxes within a modal to narrow down my search results. However, I have encountered an issue where when I check multiple checkboxes and then close the modal, the checked inputs become unchecked. Every time I open the modal, I want the check ...

What is the process for customizing the appearance of a prop within the <TextField> component?

Using my custom DatePicker.js component, I have two instances of <TextField>. When the user clicks on the <CalendarIcon> within the <TextField>, a small calendar pops up. However, I want to style the label in the <TextField> in a sp ...

Encountering an Internal Server error with Mongoose in Node.js

My latest project is a web application designed for photo sharing. One particular route in the app is responsible for retrieving and displaying photos from all users in the following array. This is the route: router.get('/getphotos',function(r ...

Tips for implementing Vue in production mode with vue.esm-bundler.js

Currently, I am utilizing Vue 3 with webpack and loading it using vue.esm-bundler.js due to the presence of in-dom templates. The documentation mentions that when using a bundler, you need to "Leaves prod/dev branches with process.env.NODE_ENV guards (mus ...

Unlocking the power of setting global variables and functions in JavaScript

Within my language.js file, the following functions are defined: function setCookie(cookie) { var Days = 30; //this cookie will expire in 30 days var exp = new Date(); exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); document.cookie = coo ...