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

Knockout Observable Array causing UI to freeze and not refresh properly

I recently started using knockout and am exploring the use of observable arrays to track changes from the UI. The initial data is loaded into the array and I'm attempting to dynamically add new objects to the array from another screen. Although I hav ...

Remove padding in Twitter Bootstrap table cells

One of my current projects requires making a button that fills the entire width and height of the TD element. I have attempted setting the normal .btn-warning with -Xpx!important, but it did not produce the desired result. Here is what I currently have: ...

Generate a menu submenu allowing for interactive toggling and dynamic visualization of expandable/collapsible sections upon clicking, featuring visually

Looking for assistance in creating a dynamic menu with sub-menus that can expand upon clicking. The goal is to have an expandable menu structure where the user can click to expand or collapse certain sections. However, my current code is not functioning co ...

What could be causing this issue with the ng-bind and ng-show directives not functioning as expected?

Attempting to show data retrieved from Google's Place Service. Oddly enough, the object can be logged to the console within the controller, but the directives in the HTML file remain blank. Since no map is being used, a div element was passed as the n ...

Get rid of the white border surrounding the object tag

Help needed in removing a thin white border around the object tag. Below is the code snippet and what has been attempted: .hr-ob { background-color: #003262; width: 50px; height: 10px; border: none; outline: none; ...

Responsive Bootstrap 5+ carousel featuring cards tailored to different viewport sizes

After an extensive search, I have come across numerous outdated questions and answers regarding my issue. With Bootstrap continuously evolving, I am hoping someone can help me with my specific requirement. I am in need of a carousel of cards that adjusts ...

Having trouble triggering the onclick event on a dynamically created table using JavaScript

I am facing an issue with adding a table programmatically that has an onclick event triggering a specific JavaScript function using the row's id for editing purposes. Unfortunately, the function is not being called as expected. I have attempted to mod ...

Creating a dynamic JSTree that loads data on demand using Stored Procedures

Currently in my SQL Server database, I have two Stored Procedures that are responsible for extracting data from a tree structure: One procedure retrieves all nodes at a specific level based on the provided level number. The other procedure retrieves th ...

When getStaticPaths and getStaticProps are programmed to deliver results

Seeking assistance with my first attempt at using getStaticPaths and getStaticProps in nextJS as a beginner. Can anyone help me resolve this issue? const datas = [ { id: 1, name: "Banheiro", image: "https://res.cl ...

"Using HTML to assign a unique identifier to an image within

Apologies in advance for any errors as I am relatively new to html. I am attempting to construct a table with images that have onclick events, so that each clicked seat is tracked and its id is added to a list to change the class. Each image has been give ...

What is the significance of the A tag when parsing a URL?

So, I encountered a problem that involved parsing a URL to extract the hostname and pathname, then comparing the extracted pathname with a string. If you need help with this issue, check out this post: How do I parse a URL into hostname and path in javasc ...

Incorporating Angular module into the mean.io bundle

Need help with adding the angular-ui-grid module to a mean.io package: $ cd packages/custom/mypackage $ npm install angular-ui-grid --save To import the JS, add this line to packages/custom/mypackage/public/index.js: import 'angular-ui-grid'; ...

Exploring the compatibility of Husky with Typicode using Yarn

Currently, I have implemented the use of husky to configure git hooks for prettier. However, I am facing a persistent issue whenever I attempt to commit or push: > husky - Can't find npm in PATH. Skipping precommit script in package.json My curre ...

Setting up an Express route for updating data

I am in the process of developing a MEVN stack CRUD application (Vue, Node, Express, MongoDB). I am currently working on setting up an Express route for handling updates in my app... postRoutes.post('/update/:id', async(req, res)=> { cons ...

How to extract an inner array from a serialized string-array

Currently, I am in the process of developing a REST-API and to populate my database, I am utilizing large JSON files containing existing data. However, I have encountered an issue with deserializing one of the fields. The structure of the JSON file is as ...

What is the proper way to provide an ajax response in order to fill up this jQuery variable?

My objective is to make the jQuery script below work with AJAX. Currently, it successfully populates my search box (<input type="text" id="search-names">) when I manually define UserArray: $(function() { var UserArray = [ {"label" ...

What action is triggered on an Apple iPhone when a notification is tapped?

Currently, I am working on a React application and testing it on an Apple mobile phone. One issue I encountered is that when I receive an SMS, the number appears as a suggestion above the keyboard. I want to be able to tap on this number and have it automa ...

Tips on utilizing browser.getCurrentUrl() within a Protractor examination

I’ve been wrestling with these lines of Protractor code today: element(by.linkText("People")).click(); browser.waitForAngular(); var url = browser.getCurrentUrl(); ... It seems that getCurrentUrl always throws an error when placed after a waitF ...

Backdrop styling for Material-UI dialogs/modals

Is there a way to customize the semi-transparent overlay of a material-ui dialog or modal? I am currently using material-ui with React and Typescript. https://i.stack.imgur.com/ODQvN.png Instead of a dark transparent overlay, I would like it to be transp ...

What is the process for populating a checkbox with data from a configuration file using JavaScript?

I have a requirement where I need to populate a list of checkboxes with data from a configuration file. To elaborate, if my checkboxes are meant to select sports, within my JSON configuration file I have an array like this: sports: ["Tennis", "Rugby", "S ...