Counting JQuery Classes in an HTML Document

My task involves creating a dynamic HTML form that allows users to enter card values, which are then counted and styled accordingly. Each set of cards is contained within a <section> element.

However, I encountered an issue with my jQuery code where it only counts and styles cards within one section. If users input cards into multiple sections, the code fails to differentiate between them. For example, if there are 2 sections, the cards in the first section should be blue while the cards in the second section should be red. Currently, all cards are showing up as blue.

jsfiddle

var numCard = $('.cards').length;
if (numCard == "2") {
  /* $('.cards').css('color', 'red'); */
  $("section .cards").parent().addClass("two-cards");
} else if (numCard == "3") {
  $("section .cards").parent().addClass("three-cards");
} else {
  $('section .cards').parent().addClass("four-cards");
}
body {
  padding: 20px;
  font-family: Helvetica;
}

.two-cards .cards {
  color: red;
}

.three-cards .cards {
  color: green;
}

.four-cards .cards {
  color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
  <div class="cards">
    First Card
  </div>
  <div class="cards">
    Second Card
  </div>
  <div class="cards">
    Third Card
  </div>
  <div class="cards">
    Third Card
  </div>
</section>
<p>

  <section>
    <div class="cards">
      First Card
    </div>
    <div class="cards">
      Second Card
    </div>
  </section>

Answer №1

Check out this working fiddle

To achieve the desired effect, you can iterate through the sections and use the this keyword for reference:

$('section').each(function() {
  var numCard = $('.cards', this).length;

  if (numCard == "2") {
    $(this).addClass("two-cards");
  } else if (numCard == "3") {
    $(this).addClass("three-cards");
  } else {
    $(this).addClass("four-cards");
  }
});
body {
  padding: 20px;
  font-family: Helvetica;
}

.two-cards .cards {
  color: red;
}

.three-cards .cards {
  color: green;
}

.four-cards .cards {
  color: blue;
}
<script src="https://examplecdn.com/jquery.min.js"></script>
<section>
  <div class="cards">
    First Card
  </div>
  <div class="cards">
    Second Card
  </div>
  <div class="cards">
    Third Card
  </div>
  <div class="cards">
    Fourth Card
  </div>
</section>
<p>
  <section>
    <div class="cards">
      First Card
    </div>
    <div class="cards">
      Second Card
    </div>
  </section>
</p>

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

Enhance the performance of page loading and implement a consistent spinner feature to ensure smooth transitions for users in Next.js version 13

I am currently working on a project using Next.js 13, and I am encountering issues with slow loading times and an unstable spinner when navigating between pages. Specifically, when transitioning from the home page to the /example page, the experience is n ...

Create a static div and a separate scrolling div

I am looking to achieve a layout where the top div is fixed at the top of the screen and the second div is scrollable below it. Both divs should have the same column width. I attempted to use position: fixed, but the columns are not aligned directly benea ...

Utilizing mat dialog in conjunction with the bootstrap sticky top class to enhance functionality

I am encountering an issue where, upon clicking to delete an entry, a mat dialog should appear with everything else in the background greyed out. However, the problem I am facing is that when I attempt to delete an entry, the dialog appears but the sticky ...

What is the best way to incorporate my Switch component into my Table component as a distinct column, while also maintaining separate states for each component?

My journey into learning React.js has been exciting so far. However, I am facing some confusion when it comes to stateful components. Currently, I am utilizing Bootstrap tables for creating a table and successfully fetching data using GET requests. Additio ...

Unexpected bug encountered while implementing redux

I received a warning from eslint while working with create-react-app. ./src/components/auth.js Line 24: Unexpected labeled statement no-labels Line 24: 'authenticated:' is defined but never used ...

Can you navigate between slides with JQuery?

Looking to create a website similar to . The only obstacle I am encountering is understanding the code. I prefer using JQuery over MooTools. Is there anyone who can kindly assist me by providing a demo? I want to implement the functionality of switching b ...

Guide on aligning a non-fixed child within a fixed parent container

I am working on a project with a fixed container (div#popup) that has some CSS styling. The container is set to position:fixed, with specific dimensions, border radius, and background color. Within this fixed container, there is a form element that I am h ...

Is it possible to eliminate the border on an image input button?

Here is the code I've been working on: HTML: <!DOCTYPE html> ... <form> <input type="image" value=" " class="btnimage" /> </form> ... CSS: .btnimage { width: 80px; height: 25px; background:url('C:/Users ...

Updating the background image without having to validate the cache

I have implemented a basic image slideshow on my website using a simple Javascript function. The function runs every 5 seconds to update the CSS "background-image" property of a div element. While it is functional, I've noticed that each time the func ...

The dropdown menu in codeigniter is not displaying the selected option

When using a drop-down button to select an option from the available choices, I encountered a problem where the selected option was not displayed in the box. Additionally, it only allowed me to make one selection. The data for the drop-down menu is retriev ...

Determining if an emitted event value has been altered in Angular 4

I am currently working on an Angular 4 project. One of the features I have implemented is a search component, where users can input a string. Upon submission of the value, I send this value from the SearchComponent to the DisplayComponent. The process of ...

Can the height of an input element be set to zero?

Currently, I am utilizing CSS transitions to adjust the height of an input element from 40px to 0px in an attempt to make it disappear. While this technique works effectively for images and yields a satisfactory result, it seems to fall short when applied ...

Issue with jsPDF: PNG file is either incomplete or corrupted

I'm encountering an issue while attempting to pass Image data to the addImage function. I have tried downgrading the versions of jspdf and html2canvas, as well as experimenting with different ways to import the two libraries, but the problem still per ...

What is the title of a document that is linked behind an HTML link?

I am seeking a way to automatically retrieve documents from web pages using a Python script. The links in the HTML pages appear as follows: href="https://foo.bar/view.php?id=123456" When clicked on in a web browser, these links open the document with its ...

Challenges with loading times in extensive AngularJS applications

We are currently tackling performance issues related to the loading time of our AngularJS application. The page takes a significant amount of time to load, and we are exploring potential causes for this delay. One factor that could be contributing to the ...

Hover over to see the impressive special effect produced by Scriptaculous Effect.Appear

Having an issue with using scriptaculous Effect.Appear() as a menu option. I'm trying to create a flash-like menu using pure css and scriptaculous. I've managed to achieve the desired outcome where hovering over a box triggers a text (with displ ...

Tips for updating the position on a website using AJAX

I am developing a website that pulls data from a MySQL database and showcases it on a map. How can I implement an automatic data refresh on the webpage every second? Should I incorporate my AJAX code within a timer function? Do I need to put the PHP scri ...

Implementing pagination within an Angular 11 Mat-table with grouping feature

Encountering an interesting issue with MatTable pagination and grouping simultaneously. I have two components each with a Mat-table featuring Pagination+Grouping. ComponentOne functions smoothly without any issues. When choosing to display 5 elements pe ...

Align the center element vertically on a website with a Bootstrap 4 navigation bar

I am trying to vertically center an element on the page. It works fine until I add a Navbar, which causes the element to be centered with an offset from the height of the Navbar. How can I center the content container vertically while accounting for the Na ...

Encountering an Error 405 Method Not Allowed while attempting to send a PUT AJAX request to a PHP server using

I am currently working on implementing a REST-like application using PHP and jQuery. During my initial attempt, I encountered the following error: PUT http://... 405 (Method Not Allowed) To address this issue, I added the following lines at the beginn ...