Toggle display of caret icon in bootstrap4 dropdown depending on the presence of dropdown menu

I need to toggle caret icons based on the presence of menu items. If menu items are present, I want to display the caret icon, otherwise hide it. The dropdown menu items will be dynamically generated and I am using Bootstrap 4.

.dropdown-toggle::after {
    display: none !important;
}

The code above removes the caret symbol, but how can I dynamically show or hide it based on the presence of menu items in the dropdown?

.dropdown-toggle::after {
    display: none !important;
}
<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>


<div class="dropdown">
    <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">
      Dropdown button
    </button>
    <div class="dropdown-menu">
      <a class="dropdown-item" href="#">Link 1</a>
      <a class="dropdown-item" href="#">Link 2</a>
      <a class="dropdown-item" href="#">Link 3</a>
    </div>
  </div>

Answer №1

To hide the shopping cart icon, use the .hide() function if there are no items inside the dropdown menu.

$( document ).ready(function() {
  if($('.dropdown-menu .dropdown-item').length==0 )
  {
   $('.fas.fa-shopping-cart').hide();
  }
});
<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">



<div class="dropdown">
    <button type="button" class="btn dropdown-toggle" data-toggle="dropdown">list<i class="fas fa-shopping-cart"></i>
 
    </button>
    <div class="dropdown-menu">
      <a class="dropdown-item" href="#">Link 1</a>
      <a class="dropdown-item" href="#">Link 2</a>
      <a class="dropdown-item" href="#">Link 3</a>
    </div>
</div>

To style using CSS only, use the only-child selector:

.dropdown button:only-child .fas.fa-shopping-cart{
display:none;
}
    <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.1.0/css/all.css" integrity="sha384-lKuwvrZot6UHsBSfcMvOkWwlCMgc0TaWr+30HWe3a4ltaBwTZhyTEggF5tJv8tbt" crossorigin="anonymous">



    <div class="dropdown">
        <button type="button" class="btn dropdown-toggle" data-toggle="dropdown">list<i class="fas fa-shopping-cart"></i>
     
        </button>
    </div>

Answer №2

Create a special class called .hidden and apply the CSS property display:none to it, as shown below.

.hidden {
display:none !important
}

Then, in your JavaScript code, add the following:

    $(document).ready(function(){


var hasElement = $(".dropdown-menu" ).has("a");

   hasElement.length == 0 ? $(".dropdown-toggle").addClass("hidden") : $(".dropdown-toggle").removeClass("hidden")
});

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

Loading gltf files with Three.js does not automatically update external variables

When I import a gltf object, it seems to render in the browser but I am unable to access it using an outside variable. What could be causing this issue? let loadedModel; gltfLoader.load('./assets/javaLogo.gltf', function(gltf){ loadedModel = ...

Effective ways to check for the time discrepancy between dates in moment.js

My server is set to use UTC date format and I am running my node server in UTC as well. I am looking to determine if the current time in Indian timezone (which is +5.30) is greater than 8AM, and if so, send an email notification. How can I achieve this u ...

The Bug in Microsoft Edge Blocking Scope Functionality

While this code functions flawlessly in Chrome and Firefox, it encounters difficulties performing in Edge: HTML: <ul> <li class="listItems">one</li> <li class="listItems">two</li> <li class="listItems">thre ...

Generate a randomly structured 2D array called "Array" using JavaScript

Can anyone help me with extracting a random array from a 2D named array? I've tried several solutions but none of them seem to work. var sites = []; sites['apple'] = [ 'green' , 'red' , 'blue' ]; sites['o ...

Querying jQuery - how can I accomplish this task?

I have been experimenting with the modal forms available in jQueryTools. I am interested in implementing these modal forms on one of my web pages, taking inspiration from the example provided here: However, I need to make some modifications to the example ...

What is the method to duplicate "subheadings" within an HTML table?

*I am facing a challenge with my HTML table that has col-span heading and related subheadings. I am struggling to find a way to repeat the subheading followed by the main heading. Below is the code snippet I have been experimenting with: <scri ...

Transferring information from Vue Component to Vuex storage

I am currently working with a Laravel API route that looks like this: Route::get('c/maintenances/{contractor_user_id}', 'Maintenance\Api\ApiContractorMaintenanceController@index'); The contractor_user_id parameter is dynamic ...

show data in a table that has additional margin at the top

I attempted to create a component similar to the input-group in bootstrap. I opted not to use the default input-group class of bootstrap because it doesn't allow for adding multiple buttons and input elements in the input group addon. Therefore, I dec ...

Assist in HTML to exhibit the display name property devoid of a label

Here is the code snippet I am working with: [Display(Name = "Empresa")] public string Company{ get; set; } In my ASPX file, I have: <th><%: Html.LabelFor(model => model.Company)%></th> This code generates the following output: < ...

Is there a way to convert JSON objects for transmission between Google Appscript and its HTML interface?

Google Appscript has the capability to transfer data from server-side scripting to client-side HTML. E.g. appscript.gs var htmlServ = HtmlService.createTemplateFromFile("addDetailsBookingForm"); let order_id = getSheetOrderID(sheet); //let ...

What is the best way to distinguish TypeScript types?

How should I handle comparing typescript types in this particular case? interface TableParams extends TableProps { data: Array<object> | JSX.Element } export const BasicTable = ({ data}: TableParams) => { if(typeof data == Array<object ...

Incorporating user names into socket.io chat for disconnect functionality

I've recently started using socket.io and have been developing a messaging chat feature. By adding usernames to the chat upon login and message submission, everything seemed to be working smoothly. However, I'm facing an issue with retrieving use ...

easy-to-use time logging

For my project, which is built on php/mysql/jquery technology stack, I require users to input time. However, the strict formats such as 06:00 PM or 14:00 can be quite cumbersome for users. I am looking for a solution that allows users to enter time in a m ...

How can I transfer a selected value from a unique dropdown component to react-hook-form?

I am utilizing react-hook-form for form validation in this Gatsby project. However, my dropdown component is not a <select> tag but a customized component created with divs and an unordered list. This design choice was made to meet our specific custo ...

I am looking to enhance my array of objects by implementing a filter. It is important that the filter does not allow for duplicate checkboxes with the

My website : https://i.sstatic.net/myJAf.png On the left-hand side of my webpage, there is a set of checkboxes with some repeated names that I don't want. For example, "Rice" is repeated twice but I only want it to display once. When checking the Ri ...

How can I locate a particular button within an "<li" tag, nestled within a "<div" container, using Python 3.7 and Webdriver?

After reviewing the HTML content, it seems that I have successfully located the desired element using the following command: driver.find_element_by_xpath('//div[@id="day-number-4"]') The div ID 'day-number-4' is unique on th ...

Firefox and Internet Explorer do not support CSS transitions

I'm trying to achieve a simple style with the following code: li, a { display: inline-block; } li { transition: top 0.3s; } li:hover { position: relative; top: 3px; } This style is intended to make some icons in a menu sink down ...

Search for data in Mongoose by utilizing a query object that has been obtained from a query string

After extracting and parsing a querystring from a URL, I am able to map it into an object structure like this: { '$and': [ { length: { '$gt': '2' } }, { length: { '$lt': '55555' } } ] } This object is st ...

jquery slider for inputting phone number on a mobile device

I am currently working on enhancing the user interface by implementing a feature where users can select a mobile number using a slider. The idea is that the user will choose a digit between 0 and 9 using the slider, then confirm their selection by pressing ...

The edges of the cube are not joined together

Looking for a 3D transform cube that can freely flip left and right, with the button fitting into it perfectly. I've found the CSS code to achieve this, but when I set the width of the ".cube" below 200px, the borders of the cube don't connect. I ...