Each container has its own div counter

Help needed to complete this code. The task is to count the number of .resp-containers in each container separately. Then, based on that count, assign a corresponding class to each element within the containers. Check out the code here

$(document).ready(function(){
    var getLength = $(".resp-container").length
    var item = $(".resp-container");
    switch (getLength) {
    case 1: item.addClass("full-resp");
    break;
    case 2: item.addClass("half-resp");
    break;
    case 3: item.addClass("third-resp");
    break;
    case 4: item.addClass("fourth-resp");
    break;
    default: item.addClass("fourth-resp"); 
}
});

HTML

<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>
</div>
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>

</div>
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
</div>
<div class="container">
  <div class="resp-container"></div>
</div>

Answer №1

If you need to apply different classes based on the number of elements found, you can utilize the .each() method as demonstrated in the example below:

$(document).ready(function(){
  $(".container").each(function(){
    var getLength = $(this).find('.resp-container').length;
    
    var item = $(this).find('.resp-container');
switch (getLength) {
  case 1: item.addClass("full-resp");
    break;
  case 2: item.addClass("half-resp");
    break;
  case 3: item.addClass("third-resp");
    break;
  case 4: item.addClass("fourth-resp");
    break;
  default: item.addClass("fourth-resp"); 
}
  })
  
 
});
.container {
  width: 100%;
}
.resp-container {
  background: blue;
  height: 50px;
  margin: 10px;
  display: inline-block;
}

/* Responsive classes */
.full-resp {
  width: 100%;
}
.half-resp {
  width: 50%;
}
.third-resp {
  width: 33%;
}
.fourth-resp {
  width: 25%;
}
@media screen and (max-width: 780px){
  .half-resp, .third-resp, .fourth-resp {
  width: 50%;
}
}
@media screen and (max-width: 661px){
  .half-resp, .third-resp, .fourth-resp {
  width: 100%;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>
</div>
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>

</div>
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
</div>
<div class="container">
  <div class="resp-container"></div>
</div>

Answer №2

To achieve the desired outcome, CSS can be utilized instead of relying on a script for improved efficiency.

Below is a Stack snippet demonstrating this:

.resp-container:first-child:last-child {
  width: calc(100% - 15px);
}

.resp-container:first-child:nth-last-child(2),
.resp-container:first-child:nth-last-child(2) ~ .resp-container  {
  width: calc(50% - 15px);
}

.resp-container:first-child:nth-last-child(3),
.resp-container:first-child:nth-last-child(3) ~ .resp-container  {
  width: calc(33.333% - 15px);
}

.resp-container:first-child:nth-last-child(4),
.resp-container:first-child:nth-last-child(4) ~ .resp-container  {
  width: calc(25% - 15px);
}

/*  for this demo  */
.resp-container {
  display: inline-block;
  height: 30px;
  background: red;
  margin: 5px;
}
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>
</div>
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>

</div>
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
</div>
<div class="container">
  <div class="resp-container"></div>
</div>

Answer №3

Why not try a simple CSS solution instead of complicating things with jQuery or extra classes:

.container {
  display: flex;
}
.resp-container {
  height: 30px;
  background: red;
  margin: 5px;
  flex:1;
}
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>
</div>
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>

</div>
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
</div>
<div class="container">
  <div class="resp-container"></div>
</div>

Answer №4

Through addressing your inquiry, I've gained valuable insights into jQuery. Allow me to share the solution:

Utilize the .each() method, $(HTMLElement) to convert this back to a jQuery object, and .children() to locate the desired resp-container.

$(document).ready(function() {
  var container = $(".container");
  container.each(function() {
    var items = $(this).children(".resp-container");
    switch (items.length) {
      case 1:
        items.addClass("full-resp");
        break;
      case 2:
        items.addClass("half-resp");
        break;
      case 3:
        items.addClass("third-resp");
        break;
      case 4:
        items.addClass("fourth-resp");
        break;
      default:
        items.addClass("fourth-resp");
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>
</div>
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
  <div class="resp-container"></div>

</div>
<div class="container">
  <div class="resp-container"></div>
  <div class="resp-container"></div>
</div>
<div class="container">
  <div class="resp-container"></div>
</div>

Answer №5

Opt for vanilla JavaScript over jQuery:

const responsiveClasses = ['full-resp', 'half-resp', 'third-resp', 'fourth-resp'] // Array containing classes to be added
const containersList = document.querySelectorAll('.container'); // Select all .container elements

containersList.forEach(container => {
    const respContainers = container.querySelectorAll('.resp-container'); // Select child .resp-container elements
    respContainers.forEach((rContainer, index) => {
        if (index < responsiveClasses.length) return rContainer.classList.add(responsiveClasses[index]);
        rContainer.classList.add(responsiveClasses[responsiveClasses.length - 1]); // Add the last defined class if no specific one is found
    })
})

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

What methods does Google use to catalogue web pages that load dynamically through jQuery?

Similar Query: Does Google crawl AJAX content? In my forum, the URLs follow a specific format for course pages such as COURSE PAGE - http://www.example.com/course/course-feed/course_id/1 Each course page contains numerous questions, with each questio ...

Bringing a JavaScript function into a TypeScript file results in it being treated as a namespace

Trying to bring a vanilla JavaScript function into a TypeScript file within a React Native app has presented some challenges. The import process goes smoothly when working with JS, but switching to TS triggers the error message: Cannot use namespace &apos ...

Observing the state object in Pinia does not trigger when the object undergoes changes

I am facing an issue with setting a watcher on a deeply nested object in my Pinia state. export const useProductStore = defineStore("product", { state: () => ({ attributes: {}, }), }); When the object has data inside it, it looks something like ...

What could be causing my js.erb file to not function properly?

Here is the code snippet I am working with: file.js.erb alert("Alert"); main.js jQuery.ajaxSetup({ 'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} }) jQuery.fn.submitWithAjax = function() { this.submit( ...

Can you provide me with steps to customize my mouse cursor specifically when hovering over the canvas?

I own a .cur file and I desire to utilize that specific cursor image whenever my mouse hovers over the canvas element in Google Chrome. <body> <canvas id="canvas" width="600" height="405" style="position:relative; background: black;" onc ...

Tips for transferring a JavaScript variable to PHP with AJAX

I am encountering an issue while trying to transfer a JavaScript variable, obtained from clicking a button, to PHP in order to execute a MySQL query. Here is my code: function ajaxCall(nodeID) { $.ajax({ type: "POST", url: "tree.php", data: {activeNode ...

PHP and Ajax Form Submission Directing to Backend PHP Script

While working on a portfolio, I encountered an issue with the contact form. When I click the submit button to send a message, instead of displaying the bootstrap alert message below the form, the page redirects to the PHP file. Although I receive the emai ...

Having trouble with retrieving JSONP data? Unsure how to access the information?

Why do I keep getting a -403 error? https://i.stack.imgur.com/T53O9.png However, when I click on the link, I see this: https://i.stack.imgur.com/8GiMo.png How can I retrieve the message? ...

"What is the best way to retrieve the id of the element that triggered a JavaScript onclick

I'm facing an issue with my GridView where I have information displayed in each row. When a user clicks on a row, more related information is supposed to be shown in a separate DIV. However, I am unable to target the specific row when trying to change ...

Tracking a user's path while redirecting them through various pages

Recently, I created a website with a login page and a home page using nodejs, javascript, and html. The client side sends the entered username and password to the server, which then replies based on the validation result. During navigation between pages, h ...

Angular Controller is not able to retrieve the Route Parameter, resulting in a 404

Currently working on my very first web app using Node.js and AngularJs. I've encountered a roadblock with the following code: var app = angular.module('Martin', ['ngResource','ngRoute']); app.config(['$routeProvide ...

Next-Auth: Access Session in _app.js Directly Without Using getServerSideProps

When working with React.js and React-Auth, it's important to note that calling server-side functions such as getServerSideProps can prevent you from exporting your project using next export. Below is the content of my pages/_app.js, which I structured ...

From SketchUp to Canvas

I've been trying to figure out how to display a 3D model created in SketchUp on a web page. After discovering three.js and exporting the model to a .dae file for use with ColladaLoader, I still can't get it to appear on my canvas. (I'm using ...

Transforming a React, Redux, and MUI Menu into an Electron Application

I'm in the process of transforming a web-based React + Redux + MUI application into an Electron app. The original app features a main AppBar with multiple dropdown menus, each containing menu items that interact with the app's Redux store. While ...

Extract data from input field and transfer to another page using ajax without needing to submit the form

My form includes an email input field: <input type="email" id="email" name="email"/> There is also a verify button: <span style="cursor:pointer"> <p id="verify">Verify</p> </span> Upon clicking the verify button, a new in ...

passport-local-mongoose req.user is currently not defined

While implementing passport js with the passport local mongoose plugin, I am facing a specific issue. Account creation and logging in are functioning properly. However, once logged in, passport fails to recognize me as a logged-in user. The code snippets ...

Having issues with default sorting and searching not functioning in Datatables with Angularjs

Utilizing a directive to facilitate database building once ng-repeat has completed: app.directive('repeatDone', function() { return function(scope, element, attrs) { if (scope.$last) { scope.$eval(attrs.repeatDone); ...

Receiving undefined when subscribing data to an observable in Angular

Currently, I am facing an issue in my Angular project where subscribing the data to an observable is returning undefined. I have a service method in place that retrieves data from an HTTP request. public fetchData(): Observable<Data[]> { const url = ...

What is the best way to give a video a border-radius in an HTML/CSS code?

Is there a way I can apply border-radius to the <video> element? This is what my video currently looks like: (image shown here: <a href="https://i.sstatic.net/izKz0.png") I attempted styling the video tag with CSS, but the changes did ...

Working with React, with the choice of incorporating jsx or not

I am currently delving into the world of React and found myself able to run a simple app without using JSX. In my JavaScript file, I started with: class TestClass extends React.Component Do I really need to utilize JSX or can I just stick with JavaScript ...