How can you determine the total number of elements with a specific class assigned to them?

I am currently using jQuery to identify which IDs have a specific class name. This information is crucial as I am employing toggleClass() from jQuery to display and hide certain divs. When a button is selected, I want a viewport to either appear or disappear. My objectives include mastering this technique in jQuery and gaining an understanding of how it can be done in pure JavaScript. I am aware that the JavaScript approach will be more complex, but I am ready for the challenge.

  1. How can I utilize the resetViewport() function to count the number of "selected" classes?
  2. Is there a more efficient method to achieve this task?
  3. In JavaScript, how can one accomplish the same functionality? Feel free to suggest specific methods in JS without providing exact code. My primary goal is to learn.

To provide clarity, I have included the code snippet. Let's begin by examining my personal website hosted at CodeAmend along with the associated code:

****html***

    <!DOCTYPE html>
<html lang="en">

... (omitted portion of HTML content)

</html>

* Here is the JavaScript / jQuery *

 $("[id^=button]").click(function () {
    $(this).toggleClass('selected');
    // Creates the ID of a viewport: "view-" + inner HTML of button
    var viewID = "#view-" + $(this).html();
    $(viewID).toggle();
    resetViewport(4);
});

function resetViewport(numberOfViewports) {
    var viewSize;
    switch (numberOfViewports) {
    case 1:
        viewSize = "400px";
        break;
    case 2:
        viewSize = "198px";
        break;
    case 3:
        viewSize = "131px";
        break;
    case 4:
        viewSize = "98px";
        break;
    }
    $("[id^=view]").css("width", viewSize);
}

Here is the CSS

    * {
    margin: 0;
    padding: 0;
}

... (omitted portion of CSS content)

Answer №1

Both jQuery collections and JavaScript NodeLists are similar to arrays, allowing you to utilize the .length property to determine the number of elements they contain.

With jQuery:

updateView($(".active").length);

In vanilla JavaScript:

updateView(document.getElementsByClassName("active").length);

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 CSS to print specific columns on a separate page at regular intervals

I am facing a challenge with printing a very large HTML table, which is dynamic in the sense that the number of rows and columns can vary. When printing, the rows that exceed the page length are automatically continued on the next page. However, I also nee ...

Sending HTML output to a PHP script

After setting up my HTML form with an action attribute pointing to "filename.php" and a method of post, I managed to generate JSON output by clicking the Submit button using the following code: $('#result').text(JSON.stringify($('form' ...

Implementing a confirmation dialog for POST requests in Flask

My first experience with Flask involves adding a confirmation dialog to a form, but only under specific conditions. Unfortunately, I'm unable to achieve this on the client side. While I was successful in implementing it for GET requests, POST requests ...

How to use Angular 2 to transform a string into an MD5 hash

While exploring the ts-md5 package, I noticed that the example code references a hashStr method, which seems to be missing now. My console displays the error: Property 'hashStr' does not exist on type Md5. After encountering this issue, I att ...

Organizing textual maps within a 2D array for rendering on an HTML5 Canvas

In my spare time, I am working on creating an HTML5 RPG game. The map is implemented using a <canvas> element with specific dimensions (512px width, 352px height | 16 tiles across, 11 tiles from top to bottom), and I'm wondering if there's ...

Is it possible to prefetch library calls in Next.js in advance?

Recently, I started working with GeoChart using react-google-charts (https://github.com/RakanNimer/react-google-charts). However, I noticed that several scripts load after the entire process is completed. In my scenario, is loading towards the end. Is t ...

Unable to save information in cookie within the success function of ajax request

When making an Ajax call to a Web API, I receive a JSON object with multiple key-value pairs. In order to handle this response data, I am utilizing jquery.cookie.js from https://github.com/carhartl/jquery-cookie. However, I encounter an error "Uncaught Typ ...

Experience real-time updates in Internet Explorer

$('#<%=ddl.ClientID%>').on("change", function () { displayLoadingPanel(); }); ddl refers to a dropdownlist. Whenever the selected value in the dropdownlist changes, I want to show a loading panel. This code works well in all browsers excep ...

Tips for transferring data between two forms in separate iFrames

I'm trying to achieve a functionality where the data entered in one form can be submitted to another form within an iframe. The idea is to allow visitors to preview their selected car in the iframe, and if satisfied, simply press save on the first for ...

Trigger the Input event on Android with Nuxt

A unique issue has arisen with an input field that filters a list whenever a key is pressed, displaying the filtered results in the browser. While the functionality works perfectly on desktop, it behaves strangely on Android mobiles. The list only shows up ...

Unexpected updates occurring in custom Google Sheet functions

Currently, I am utilizing a personalized function to retrieve price data for EVE Online. However, I am encountering an issue where the function is updating every 10-20 minutes, leading to a depletion of my daily URL Fetches quota. The primary function can ...

Guide to customizing WordPress header menu buttons with CSS, excluding a specific button

I need help with custom CSS for my WordPress site. I want to apply a hover effect to all menu buttons except for the "Contact" button, which already has its own styling. The CSS code adds a growing line beneath the hovered menu item and a static line unde ...

The compiler option 'esnext.array' does not provide support for utilizing the Array.prototype.flat() method

I'm facing an issue with getting my Angular 2 app to compile while using experimental JavaScript array features like the flat() method. To enable these features, I added the esnext.array option in the tsconfig.json file, so the lib section now includ ...

AngularJS uibModal missing dependency error

I'm encountering an issue with injecting the uibModal dependency in my app.js: Angular Version: 1.5.7 ui.bootstrap Version: 1.3.3 Bootstrap Version: 3.3.6 I keep running into this error: angular.js:13708 Error: [$injector:unpr] Unknown provider ...

What could be the reason for my PHP files not appearing in my CSS navigation tabs?

In my PHP document, I am using CSS navigation tabs to display three different files. <div id="Tum" class="w3-container training"> <h2>TUM</h2> <?php include("tum.php"); ?> </div> <div id="Atol" class="w3-container traini ...

Focusing on form field using jQuery within a Google Map interface

I am experiencing difficulties getting a focus function to work on my page, which features a large fullscreen Google map. Can anyone provide insight into why this may be happening? Due to the length of the code, I have provided the URL and some excerpts be ...

Substitute placeholders in the HTML code with Angular syntax

Lately, I have been encountering some issues with AngularJS. I have defined multiple scopes like this: app.controller('mainController', function($scope) { $scope.siteURL = "my website url"; }); When using the {{siteURL}} variable in ...

Creating dynamic values in data-tables using Vuetify

As I work with JSON data, my current task involves formatting it using Vuetify's Data Tables. The official documentation provides guidance on defining table headers as shown below: import data from './data.json' export default { data ...

Creating a dynamic and adaptive layout using Bootstrap 4

Currently, this webpage appears as follows: I attempted to organize the images in row 2 of the grid but the outcome was reversed Upon resizing to a mobile screen and switching to a flex column layout: I tried to address the overflow issue The HTML code: ...

Create a duplicate of the information stored within the $scope variable

Suppose there are multiple variables stored in a $scope and the objective is to create a new object that only includes those variables, excluding all the internal Angular-related data. The specific names of the $scope variables may not be known. This can ...