Breaking News

javascript – jQuery – If all Child elements have same class add additional class to another element on the page

Questions:

I would like to be able to check using jQuery if all child elements share the same class. If all child elements have the same class I would then like to apply an additional class to another element on the page that is not a direct child but the closest h4.

The HTML elements in question are in the attached image. The code is auto generated by a plugin.

Currently I am looking for any elements that contain 0 and the class no items is applied. This can be seen in the screenshot.

The h4 at the top of the image is the element that needs a class adding to it if all children have the class of “no-items”

Basic HTML Example

This is the element that needs a class if all li's have the class of no-items

  • 0
  • 0
  • 1
  • 0

enter image description here

How to&Answer:

This would do the trick:

$('h4').addClass(function(){
    if( $(this).next('ul').find('li').length === $(this).next('ul').find('li.no-items').length ) return 'someclass';
})

This would be applied to all h4 elements on the page so you may need to make it more specific.

What it does is look for an h4 element and add a class if the number of list items in the list that follows it equals the number of list items with the no-items class.

About rankhawks

Check Also

Android Studio e Java – Curso Para Iniciantes

Android Studio e Java – Curso Para Iniciantes – Download Udemy Courses For Free | …

Bootstrap 4 – Create 4 Real World Projects

Description THE BESTSELLING BOOTSTRAP COURSE ON UDEMY!!! INCLUDED: Typography Utilities Layout in Bootstrap CSS Flexbox …

The Complete Android P + Java Developer Course™ : 2019

The Complete Android P + Java Developer Course™ : 2019 – Download Udemy Courses For …

IOS 12: Learn To Code & Build Real IOS 12 Apps In Swift 4.2

Must have a computer running macOS High Sierra or Mojave (for some sections) Should have …

Angular JS Complete Course

Angular JS Complete Course Learn to build robust Applications with the popular AngularJS framework What …

Leave a Reply

Your email address will not be published. Required fields are marked *