If the children contain multiple div elements in jQuery

Is there a way to determine the number of divs inside a li element?

Below is the code I've tried, but it's not functioning as expected. (The issue is that every img receives the class, even when there's only 1 div inside the li.)

if($('.lookbook ul li').find('div').length > 1){
    $('.lookbook ul li img').addClass('lbcursor');
}

Here is the HTML structure:

<div class="lookbook>
    <ul>
        <li>
            <div><img/></div>
            <div></div>
        </li>
        <li>
            <div><img/></div>
            <div></div>
        </li>
        <li>
            <div></img></div>
        </li>
    </ul>
</div>

The third img should not receive the class.

I need to count the number of divs in the li element, and if there's more than 1 div, the class .lbcursor should be added to the img.

I found a similar answer here on Stack Overflow, but it doesn't seem to work for my situation.

Upon further inspection, I realized that the if clause is correct. The problem lies in which elements are receiving the class.

Answer №1

To access and modify a specific element, you must iterate through all elements.

$('.lookbook ul li').each(function() {
  var $this = $(this);
  if ($this.find('div').length > 1) { // to target direct descendants, use .children('div').length
      $this.find('img').addClass('lbcursor');
  }
});

Here is a demonstration on JSFiddle

An alternative way to achieve the same result:

$('.lookbook ul li').each(function() {
  var $this = $(this);
      $this.find('img').addClass(function(){ // utilize the function argument syntax for addClass
          return $this.find('div').length > 1 ? "lbcursor" : "";
      });
});

Answer №2

Here's a neat and straightforward solution using the :has() and :nth-of-type() selectors.

$('.lookbook ul li:has(div:nth-of-type(2)) img').addClass('lbcursor');

Check out the jsFiddle Demo

  • Just a heads up - Similar to the :nth-of-type() selector, this method will only work if the div elements are direct children of the same parent (as indicated in your query).

Answer №3

The code condition appears to be correct, but the if-block is accessing all images to apply the CSS class.

To improve the code, consider rewriting it as follows:

if($('.lookbook ul li').find('div').length > 1){
   $('.lookbook ul li img').find('div').addClass('lbcursor');
}

Remember to make necessary refactorings.

Take note of the extra find() function call inside the if block.

Answer №4

To tailor each element individually, consider utilizing 'each' within this context:

$('.lookbook ul li').each(function() {
  if ($(this).find('div').length > 1) {
     $('.lookbook ul li img').addClass('lbcursor');
  }
});

[UPDATE] as mentioned

$('.lookbook ul li img').addClass('lbcursor');

needs to be

$(this).find('img').addClass('lbcursor');

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

Utilizing Jquery UI's autocomplete feature with data fetched from a

I am new to JavaScript and recently came across an autocomplete tutorial that works well. However, the autocomplete script is currently set up to handle multiple values from a database. It adds a comma after each keyword and then searches for a new keyword ...

Is it possible for me to utilize this code for logging in through a dialog box?

Here is the code snippet I have on the client side: <p>Username:</p> <p><asp:TextBox ID="tbUsername" runat="server"></asp:TextBox></p> <p>Password:</p> <p><asp:TextBox ID="tbPassword" runat="server ...

Revamp the Bootstrap 4 Form Check: Rearrange Options from left-to-right and top-to-bottom to top-to-bottom and left-to-right

I am currently using a Bootstrap form that displays a checkbox with 13 different options, including: Urban Plans Commercial Entity Cultural Approval Education Sector Hospitality Industrial Design Interiors Art Leisure/ Sporting Residential Care Retail Spa ...

ReactJS how to prevent accordion from collapsing automatically

My custom accordion layout for the features needed in the site I am building is not working well with Jquery. How can I modify it to collapse properly? Specifically, I want it so that when I open number 2, number 1 will automatically close. I've trie ...

CSS with a "true" space for a fixed element (ensuring the previous element does not overlap with the current fixed element)

I am facing an issue with the layout of my webpage. I have two horizontal columns - the left one is fixed, along with a bottom footer that is below the second content column. When I add a border to the content column, it extends all the way down to the fo ...

Unable to align my navigation bar in the center

My navigation bar code is not centering on the website. Even after removing float: left, it doesn't move to the desired position. Can anyone help me with this issue? Thank you. css ul#list-nav { list-style: none; margin: 20px auto; paddi ...

Is there a way to select a checkbox in Google Forms using the console?

I need help with a script I'm creating to automatically populate Google Forms. I am able to select checkboxes using querySelector, but they don't have a .click() method or similar. How can I go about checking the checkboxes? ...

A guide on linking a jQuery dialog to an HTML element once the data has been updated with an AJAX response

On my PHP page, I have implemented a jQuery script to open a dialog window. The code for this is as follows: <script type="text/javascript"> $(document).ready(function() { var $loading = $('<img src="loading.gif" ...

Issue with Bootstrap contact form functionality in PHP not working

I have experience in coding HTML and PHP, but unfortunately, [email protected] (mail address) is still unable to receive emails from my website (http://cloudsblack.info/) and when I click the submit button, it leads to a blank page (http://cloudsblack.info ...

What is the correct way to properly insert a display none attribute

I'm experiencing some alignment issues with the images in my slideshow. I used this example as a reference to create my slide: https://www.w3schools.com/w3css/tryit.asp?filename=tryw3css_slideshow_dots When clicking on the next image, it seems to mo ...

Removing the switcher outline in Bootstrap Switch: a step-by-step guide

I have implemented the bootstrap-switch - v3.3.1, however, I want to remove the default blue outline that appears around the switcher when toggling it on or off. Despite setting style="outline: 0 none; for the input, the outline remains visible. Below is ...

Can qTip 2.0 be configured to use a different default attribute instead of 'title'?

Is there a way to set qTip to use an attribute other than 'title' as the default? I need to use another attribute because when I disable qtip and add elements dynamically with "title", the title still shows when I hover over the element, which i ...

Eliminating the Scrollbar from Bootstrap 4 DataTable Causes Table Width to Decrease

My tables are causing a horizontal scroll bar to appear when converted to Bootstrap data tables. Adding the "p-3" class to the table's div for padding eliminates the scroll bar but also narrows the table. Is there a solution to removing the scroll b ...

Trying to showcase information received from a server using an API

For a school project, I am developing a website that can retrieve weather data (currently just temperature) based on a city or zip code from openweathermap.org using an asynchronous call. I have successfully retrieved the data from the API, but I am strug ...

AngularJS allows a function to return an array value, which can be displayed in separate blocks on

Building a program that involves working with an AngularJS array. I need to showcase the elements of the AngularJS array, returned by a function, in an organized manner. Each element should be displayed correspondingly - for example, 'first' cont ...

Is it possible to utilize JQuery $.post for file uploads?

Similar Inquiry: How can files be uploaded asynchronously using jQuery? jQuery Ajax File Upload I typically use $.post to send form data to a php page for database insertion. However, I am wondering if this same method can be used to upload files, ...

Switch up the appearance of a document by manipulating the stylesheet using a select tag

I'm currently facing an issue with the implementation of a drop-down box on my website for selecting different themes. Despite having the necessary javascript code, I am unable to get it working correctly. Here's the snippet: //selecting the sele ...

Streamlined payment with PayPal Express Checkout via AJAX

I am working on integrating a JQuery client with PayPal's Express Checkout functionality for credit card transactions. The process involves the client presenting a form to the user, initiating a purchase via AJAX to the server, executing SetExpressChe ...

Tips for utilizing the jquery columnize plugin in conjunction with AngularJs

I am looking to utilize the columnize plugin from jQuery to create columns in my AngularJS application. Initially, I attempted the following straightforward approach: .directive('columnize', function() { return { restrict: 'A&ap ...

Adjust the date input alignment in mobile browsers

I am trying to align the entered date to the left in input[type='date']. However, when testing on mobile browsers like safari and chrome, the date remains centered within the input. mobile example This is the code I have been working on: .co ...