Discovering an HTML Element in a JavaScript Array with Specific Styling: A Step-by-Step Guide

I am in the process of developing a website that consists of different sections. The concept is simple - by clicking on a button located at the bottom of the page, it will reveal the corresponding div section.

For styling purposes, I have initially hidden all four sections and made only the "home" section visible:

.container-pages {
    display: none;
}

#home-page {
    display: block;
}

As for the HTML structure, it primarily includes the sections and associated buttons:

<!--sections-->
<div id="home-page" class="container-pages">
        <h1>HOME</h1>
    </div>
    <div id="start-page" class="container-pages">
        <h1>START</h1>
    </div>
    <div id="learn-page" class="container-pages">
        <h1>LEARN</h1>
    </div>
    <div id="contact-page" class="container-pages">
        <h1>CONTACT</h1>
    </div>
    
<!--buttons-->
    <div id="bottom-menu">
        <div class="bottom-buttons bottom-menu-items" id="home-button">HOME</div>
        <div class="bottom-buttons bottom-menu-items" id="start-button">START A PROJECT</div>
        <div class="bottom-buttons bottom-menu-items" id="learn-button">LEARN</div>
        <div class="bottom-buttons bottom-menu-items" id="contact-button">CONTACT US</div>
    </div>

Next comes the JavaScript implementation:

// creating an array with the 4 html sections (pages):
const pages = [...document.getElementsByClassName('container-pages')];

// creating an array with the 4 html sections (pages):
const pages = [...document.getElementsByClassName('container-pages')];
.container-pages {
  display: none;
}

#home-page {
  display: block;
}
<!--sections-->
<div id="home-page" class="container-pages">
  <h1>HOME</h1>
</div>
<div id="start-page" class="container-pages">
  <h1>START</h1>
</div>
<div id="learn-page" class="container-pages">
  <h1>LEARN</h1>
</div>
<div id="contact-page" class="container-pages">
  <h1>CONTACT</h1>
</div>

<!--buttons-->
<div id="bottom-menu">
  <div class="bottom-buttons bottom-menu-items" id="home-button">HOME</div>
  <div class="bottom-buttons bottom-menu-items" id="start-button">START A PROJECT</div>
  <div class="bottom-buttons bottom-menu-items" id="learn-button">LEARN</div>
  <div class="bottom-buttons bottom-menu-items" id="contact-button">CONTACT US</div>
</div>

Now, my challenge lies in filtering this array to create a new one containing only the <divs> that are currently displayed with the style attribute set to display: block;.

I attempted the following approach:

const currentSelection = pages.filter(div => div.style.display === 'block');

However, upon logging the currentSelection array to the console, it returns empty. Any insights or assistance on this matter would be greatly appreciated!

Thank you, Menmoe.

Answer №1

One convenient method is to consider that

element.style.display === 'block'
will only match if the inline style attribute has set display: block. If the styles are defined in a stylesheet or within a <style> element, then we should utilize
window.getComputedStyle(element, state).propertyName
to retrieve the computed properties applied to the element:

// an array containing 4 sections of HTML (pages):
const pages = [...document.getElementsByClassName('container-pages')],
// using Array.prototype.filter() along with an anonymous Arrow function
// to retain elements from the 'pages' Array based on 'display' being 'block':
visible = pages.filter((page) => window.getComputedStyle(page, null).display === 'block'),
// filtering for pages that have 'display: none':
hidden = pages.filter((page) => window.getComputedStyle(page, null).display === 'none');

console.log(visible, hidden);
.container-pages {
  display: none;
}

#home-page {
  display: block;
}
<!--sections-->
<div id="home-page" class="container-pages">
  <h1>HOME</h1>
</div>
<div id="start-page" class="container-pages">
  <h1>START</h1>
</div>
<div id="learn-page" class="container-pages">
  <h1>LEARN</h1>
</div>
<div id="contact-page" class="container-pages">
  <h1>CONTACT</h1>
</div>

<!--buttons-->
<div id="bottom-menu">
  <div class="bottom-buttons bottom-menu-items" id="home-button">HOME</div>
  <div class="bottom-buttons bottom-menu-items" id="start-button">START A PROJECT</div>
  <div class="bottom-buttons bottom-menu-items" id="learn-button">LEARN</div>
  <div class="bottom-buttons bottom-menu-items" id="contact-button">CONTACT US</div>
</div>

Another simpler way could be using the hidden attribute to hide relevant elements:

// creating an array with the 4 html sections (pages):
const pages = [...document.getElementsByClassName('container-pages')],
// filtering elements in the 'pages' Array based on their 'hidden' property being false (visible):
visible = pages.filter((page) => page.hidden === false),
// a similar approach for filtering out hidden pages:
hidden = pages.filter((page) => page.hidden === true);

console.log(visible, hidden);
<!--sections-->
<div id="home-page" class="container-pages">
  <h1>HOME</h1>
</div>
<div id="start-page" class="container-pages" hidden>
  <h1>START</h1>
</div>
<div id="learn-page" class="container-pages" hidden>
  <h1>LEARN</h1>
</div>
<div id="contact-page" class="container-pages" hidden>
  <h1>CONTACT</h1>
</div>

<!--buttons-->
<div id="bottom-menu">
  <div class="bottom-buttons bottom-menu-items" id="home-button">HOME</div>
  <div class="bottom-buttons bottom-menu-items" id="start-button">START A PROJECT</div>
  <div class="bottom-buttons bottom-menu-items" id="learn-button">LEARN</div>
  <div class="bottom-buttons bottom-menu-items" id="contact-button">CONTACT US</div>
</div>

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

Automatically fill out form fields by selecting data from a spreadsheet

I successfully created a web application using Google Apps Script (GAS) that sends data on submission to Spreadsheet A. Furthermore, I have implemented a select option that dynamically fetches data from another spreadsheet B ("xxx") in column A. Below is ...

What causes the div to not adjust to the browser window when the vertical size is decreased?

Imagine a basic HTML page like this: <doctype> <html> <head> <title>My Amazing Page</title> <script type="text/javascript" src="jquery-1.8.3.min.js"></script> </head&g ...

Utilizing a percentage for the border-width property

I want to remove a triangle from the bottom of a div using a CSS trick involving borders. This involves creating a border with one transparent side and coloring the other sides to create the triangle effect. The issue I'm facing is that the div has a ...

Is there a way to use jQuery draggable to move a zoomed image within a div clipping mask?

Looking to enhance user experience, I am developing an interface that allows users to zoom in on an image and move the zoomed version within a clipping mask div. I have created a div with dimensions of 200px by 200px and set overflow: hidden. Then, I inse ...

What is the best technique for evaluating different businesses' operating hours?

I am trying to compare the opening hours stored on my server with the current time. Here are the details: Start: 09.00 End: 00.30 The goal is to determine if the store is open or closed based on the current time. If the current time falls outside of t ...

Execute AJAX request for two individual buttons

I have a scenario where I want to use two buttons to open separate PHP pages, but I would like to trigger both buttons with a single function. The AJAX function should then determine which button was clicked and open the corresponding PHP page - for exam ...

I am having trouble placing items correctly into my array using C programming

int main(void){ char name[8], comName[24]; int numComponents, numSchemes, i; printf("\n\nHow many marking components in the course? "); scanf("%d", &numComponents); char *listComponents[numComponents]; i=0; whil ...

React: Using useState and useEffect to dynamically gather a real-time collection of 10 items

When I type a keystroke, I want to retrieve 10 usernames. Currently, I only get a username back if it exactly matches a username in the jsonplaceholder list. For example, if I type "Karia", nothing shows up until I type "Karianne". What I'm looking f ...

Is it possible to achieve this shaded gradient effect using CSS3?

Check out this image for reference. I've managed to style a horizontal rule using SVG as the background image, creating a specific effect. However, I am struggling to achieve the same result using CSS3 alone. If there are any CSS experts who can adv ...

Having trouble accessing the value of a node in JavaScript, as it keeps returning as "null"

Experimenting with converting HTML elements into lists. The objective is to generate a list of all values in a table upon clicking the "page next" buttons on it. Afterward, an alert should display the value of the first item in the list, which corresponds ...

the components progress down the line

For my right column implementation, I decided to use CSS position:relative and put different elements inside in position:absolute as shown below: <!-- Right Column --> <div class="col-xs-3 pl18" style="position:relative;"> <!-- Withou ...

Ways to conceal the contents of a page behind a transparent background div while scrolling

I created a Plunkr with the following markup: <body> <div class="container-fluid"> <div class="row"> <div class="col-sm-12"> <nav class="navbar navbar-fixed-top"> <div class="container-fluid"& ...

Switching a material-ui input control instead of a textfield for materials-ui-datepicker: the ultimate guide

Within my React application (v16.3), I am utilizing the DatePicker component from the material-ui-pickers library to render date-picker controls. This particular component renders a Material-UI TextField. However, I am interested in modifying it to only di ...

When activating another function, Javascript failed to trim and hide the div as intended

Before adding another function (*2), my function (*1) was working perfectly. However, after adding the second function, there seems to be a conflict and now it's not working as expected. :( <script type="text/javascript> $(function() { ...

I'm trying to retrieve information from openweathermap in order to show it on my app, but I keep running into an error that says "Uncaught RangeError: Maximum

I recently created a div with the id 'temporary' in order to display data retrieved from the openweathermap.org API. However, I am encountering an error in the console and I'm not sure why. This is my first time working with APIs and I would ...

How can AngularJS effectively parse JSON data containing HTML elements?

We are experiencing difficulties in reading a json file containing html content. Here is the code snippet with the json data we are working with: Json data: { "aboutContent": { "listItems": [{ "title": "Investors", "de ...

Issue with Vue 2: Promise does not resolve after redirecting to another page

Although I realize this question might seem like a repetition, I have been tirelessly seeking a solution without success. The issue I am facing involves a method that resolves a promise only after the window has fully loaded. Subsequently, in my mounted h ...

Exploring Angular2: The Router Event NavigationCancel occurring prior to the resolution of the Route Guard

My application has routes protected by an AuthGuard that implements CanActivate. This guard first checks if the user is logged in and then verifies if certain configuration variables are set before allowing access to the route. If the user is authenticated ...

Displaying infowindow pop-ups on random markers on Google Maps every 3 seconds

Here lies the challenge. I am tasked with creating a Google map that displays multiple markers. Each marker must have a unique info window with distinct content. Upon opening the website, an info window randomly appears on one of the markers after 3 sec ...

Use Vue JS to send a GET request to the server with custom header settings

When creating a Vue.js component, I want to send a GET request to a server with specific headers. How can I achieve this? Using cURL: -X GET "http://134.140.154.121:7075/rest/api/Time" -H "accept: application/json" -H "Authorization: Bearer eyJhbGciOiJSUz ...