Hide the element with the attribute data-id if its value is null

My menu displays items that correspond to content on another list.

MENU

<ul id="gallery-list" style="display: none;">
        <li class="close"></li>
        <li data-id="9425"><strong>item 1</strong></li>
        <li data-id="9426"><strong>item 2</strong></li>
        <li data-id="9488"><strong>item 3</strong></li>
        <li data-id="9489"><strong>item 4</strong></li>
        <li data-id="9495"><strong>item 5</strong></li>
        <li data-id="9427"><strong>item 6</strong></li>
</ul>

CONTENT:

<ul id="gallery-container">
        <li data-id="9425">
            <h3 style="display: none;">Item 1</h3>
            <div class="content">Content here</div>
        </li>
        <li data-id="9426">
            <h3 style="display: none;">Item 2</h3>
        </li>
        <li data-id="9488">
            <h3 style="display: none;">Item 3</h3>
        </li>
        <li data-id="9489">
            <h3 style="display: none;">Item 4</h3>
        </li>
        <li data-id="9495">
            <h3 style="display: none;">Item 5</h3>
            <div class="content">Content here</div>
        </li>
        <li data-id="9427">
            <h3 style="display: none;">Item 6</h3>
            <div class="content">Content here</div>
        </li>
</ul>

Some items have a .content class within the li in the content section. How can I use the data-id attribute to show only relevant items in the menu? Essentially, only items with a .content class should be displayed in the menu.

The desired output for the MENU is as follows:

<ul id="gallery-list" style="display: none;">
        <li class="close"></li>
        <li data-id="9425"><strong>item 1</strong></li>
        <li data-id="9495"><strong>item 5</strong></li>
        <li data-id="9427"><strong>item 6</strong></li>
</ul>

An alternative acceptable format could be:

<ul id="gallery-list" style="display: none;">
        <li class="close"></li>
        <li data-id="9425"><strong>item 1</strong></li>
        <li data-id="9425" style="display:none;"><strong>item 2</strong></li>
        <li data-id="9425" style="display:none;"><strong>item 3</strong></li>
        <li data-id="9425" style="display:none;"><strong>item 4</strong></li>
        <li data-id="9495"><strong>item 5</strong></li>
        <li data-id="9427"><strong>item 6</strong></li>
</ul>

Note that items in the content are initially set to display:none;.

This script manages the display of list contents and activates the menu:

    $("#gallery-list li").click(function() {
        var id = $(this).data('id');
            $("#gallery-container").find('li').each(function() {
            $(this).find('.content').toggle($(this).data('id') === id);
            $(this).find('h3').toggle($(this).data('id') === id);
        });
    });
    window.onload = function () {
        $("#gallery-container li .content").css("display", "none");
        $("#gallery-container li h3").css("display","none");
        $("#gallery-container li p").css("display","none");
    }
    $('.gallery-menu h3, #gallery-list li').click(function(){
        $("#gallery-list, .gallery-menu h3").toggle();
    });

This functionality controls the visibility of list items based on the content's .content class and triggers the menu.

Answer №1

One suggestion I have is to loop through the content list items and if there is no .content available inside, then go ahead and remove the related menu item.

$(function() {
    $("#gallery-container li[data-id]").each(function() {
        if( $(".content", this).length == 0 ) {
            $("#gallery-list li[data-id=" + $(this).data("id") + "]").remove();
        }
    });
});

@XerenNarcy mentioned in a comment that you can also use a combination of not() and has():

$(function() {
    $("#gallery-container li[data-id]:not(:has(.content))").each(function() {
        $("#gallery-list li[data-id=" + $(this).data("id") + "]").remove();
    });
});

Instead of using remove(), you could consider using hide() as well.

Check out a working example here.

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

Setting a default value dynamically in a `select` control can be done by using JavaScript to

Upon subscribing to the HTTP server for data retrieval, my select control in Angular framework gets loaded with the received data. My objective is to set a default value that comprises three values from the server object separated by slashes ("/"), which r ...

iPhone displaying erratic behavior with executing javascript code

I need help with the following link: <a href='external-url' class='track' data-type='event' data-category='category'> Link </a> Whenever the link is clicked, a specific function is triggered: $(&apo ...

Prevent DIV from shifting upwards while resizing the window

I am in the process of creating a responsive website, and I encountered an issue with a particular DIV that spans 100% width of the body. Whenever I resize the browser window, this DIV moves upwards and covers the one above it. This problem only occurs whe ...

Selecting an option from the dropdown will automatically toggle the checkbox on and off

I'm looking to dynamically change the checkbox selection when the dropdown value changes using jQuery. The data is sourced from a database. Here's the code snippet I currently have: $("#roles").change(function() { $.ajax({ url: ...

`Nginx with a touch of material design`

Currently, I'm in the process of implementing material design UI on a functioning web application. The application utilizes Nginx, PHP, and PostgreSQL. While I have proficiency in PHP and PostgreSQL to ensure the functionality (code composed in notepa ...

Sequelize query for filtering on a many-to-many relationship

Seeking assistance with Sequelize ORM in express.js, I have successfully implemented a many-to-many relationship between two tables. To simplify my query, imagine the tables as Users, Books, and UserBooks where UserBooks contains UserId, BookId, and an ex ...

CSS - The design structure is completely disorganized

There seems to be an issue with the CSS that is causing the layout to appear distorted. Despite my efforts to correct it, the layout remains unsatisfactory. Please review the HTML and CSS code to see if you can pinpoint the problem. I am aiming for the de ...

Is it possible to transform an array into a JSON file and securely store/upload it in an AWS S3 bucket?

Recently, I started exploring aws and its capabilities. Currently, my focus is on developing a web application that allows users to input text in two separate fields. Subsequently, this text will be converted into a Json file and stored in the S3 bucket. ...

make sure the <option> tags fit seamlessly inside a Bootstrap card

I'm currently working on a project using Angular in combination with Bootstrap 4.0. My goal is to integrate <select>, <option>, and <optgroup> elements within a card. Below is the code snippet from the component.html file: <div ...

Unexpected results with PHP's NL2BR function

I am facing a peculiar issue and need some help understanding why my nl2br function is not producing the desired result. Below is a snapshot of the data stored in mysql phpmyadmin: Additionally, I have included a screenshot of the jquery / php code used ...

How can I verify if my discord.js bot has the necessary permissions from a server or channel?

I need to verify two things: Determine if my bot has a particular SERVER permission (return true/false based on the presence of that permission) Confirm if my bot possesses a specific CHANNEL permission (return true/false depending o ...

Ways to detect if a script-blocking ad blocker like Ghostery is preventing a file from loading

I am currently working on a method to detect if ghostery is preventing google doubleclick ad scripts from being loaded. I prefer not to use a listener and instead want a straightforward way to determine if the script or URL is being blocked. Although the c ...

Desktop display issue: Fontawesome icon not appearing

Having trouble getting the fontawesome icon to display properly on my website. It appears in inspect mode, but not on the actual site itself. Any suggestions on how to fix this issue? import React, { Fragment, useState} from "react"; import { Na ...

The attempt to send a complex javascript object through AJAX to the server is unsuccessful

Looking at my JavaScript object structure, it appears as follows: var obj = { "name": "username", "userid": "9999", "object1": { "subObject1": { "subArray1": [], "subArray2": [] }, "subObject2" ...

The new button placed on a <div> was not initialized to trigger my greasemonkey functions

Recently, I implemented a button via GreaseMonkey: var input = document.createElement('input'); input.type = 'button'; input.value = 'Off'; input.onclick = turnTheWheelsofTime; Initially, the button functioned flawlessly whe ...

Transferring data from PHP to JavaScript through JSON

Seeking advice on a unique issue that sets it apart from the rest. I am successfully passing JSON data from PHP to JavaScript using the jQuery.ajax() method, but here's my dilemma: I have contact data in MySQL with fields like firstname, lastname, la ...

Obtain the text content in cases where the DOM is missing both the title and value fields

I am trying to extract the value from a text-box using selenium, but the text-box is marked as readonly and aria-live is set to off. Here is the DOM structure: <input autocomplete="off" class="abc" type="text" role="t ...

The addition of ngRoute causes the controller in AngularJS to malfunction

Currently, I am attempting to implement routes in my angularJS application and have encountered an issue where integrating 'ngRoute' into the app causes the main controller to malfunction. Furthermore, I am experiencing difficulties with ngRoute ...

When querying a web method with AJAX using JSON data, the response is coming

On my asp.net webpage, I am using html controls to save appointments to a database. To achieve this without refreshing the page, I am sending input values to the codebehind using a web method with Ajax. However, I am encountering an issue where the succeed ...

Identify when a browser tab is closed and determine which specific tab out of all the open tabs was closed

Is there a way to identify when a browser or tab is closed in Angular/JavaScript? I would like to know if there are specific events that can be used for detecting these actions. Any advice, information, or code examples on this topic would be greatly app ...