What is the formula to determine the sizes of grandchildren div containers?

Hey everyone,

I'm having some trouble with my jQuery code and I can't seem to figure out what's going on.

Here's the scenario:

I'm creating a few divs (based on entries from MySQL) and I'd like to show you the end result:

<div class="shipcontainer" id="shipcontainer1">
    <div class="timelinecontainer" id="timelinecontainer1">timeline--></div>
    <div class="travelsall" data-ship="1">
        <div class="travelcontainer" data-travelid="1" data-ship="1" id="travelcontainer1">
         <div class="fasecontainer" data-travelid="1" data-ship="1">
           <div class="Mobilize  travelfase" date-days="6" date-fasetravelid="1">1: Mobilize </div>
           <div class="Loading travelfase" date-days="12" date-fasetravelid="1">2: Loading</div>
           <div class="Boating travelfase" date-days="20" date-fasetravelid="1">3: Boating</div>
           <div class="Discharge travelfase" date-days="6" date-fasetravelid="1">4: Discharge</div>
        </div>
        <div class="options" id="optionstravel1" data-travelid="1">OPTIONS</div>
      </div>
    </div>
</div>

As you can see, there is a ship container div with two child divs (timeline container and travels all). The travels all div in this example contains only one travel container, but there will be more in the future.

This piece of code gets repeated multiple times (I currently have two ship containers).

My goal was to set the width of the div with the class ".travelcontainer" to the sum of the widths of the four divs with the class ".travelfase". Here's my jQuery code:

var totalWidth = 0;

$(".travelcontainer").width(function () {
  var travelID = $(this).data(travelid);

  $(this).find('div[data-fasetravelid=' + travelID + ']').each(function (index, element) {
    totalWidth = $(this).innerWidth() + totalWidth;
  });

  return totalWidth;
});

Since I assigned a data-travelid attribute to each ".travelcontainer" during PHP parsing and also to its grandchildren with the class ".travelfase", I thought this would work.

The issue I'm facing is that when I have two ship containers, it adds up all the values together. So, the travel container with data-travelid=1 ends up with the same width as all divs with the class "travelfase," instead of just those with the data-fasetravelid=1 attribute.

I also tried this code which I used before:

var widthTotal = 0;

$(".travelcontainer").width(function () {
  $(".travelcontainer > .travelfase").each(function (index, element) {
    widthTotal = $(this).innerWidth() + widthTotal;
  });
});

return widthTotal;

Unfortunately, this has the same effect.

If anyone can spot what I'm doing wrong, I would really appreciate your help!

Thanks in advance!

Answer №1

Give this a shot:

$(".travelcontainer").each(function() {
  var total = 0;

  $('.travelfase', this).each(function () {
    total += $(this).width();
  });

  $(this).width(total);
});

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

Using AJAX to send span values to PHP

Thank you for your time. I am currently working on integrating a visual shopping cart into several pages of a parallax website. Due to the nature of the parallax design, where each 'page' opens and closes a form independently, using a continuous ...

What is the best way to update text in an element when hovering or activating it?

I am currently designing a website with a prominently placed "Hire me" button in the center of the page. The button was implemented using the following code: <div id="hire_me_button"> <a href="contact.html"><h4 id="hire_me" class="butto ...

Can you create a stroke that is consistently the same width as the container BoxElement?

Utilizing a BoxElement provided by the blessed library, I am showcasing chat history. New sentences are inserted using pushLine. To enhance readability, days are separated by lines (which are added using pushLine). The width of each line matches that of t ...

How can I make tooltipster display tooltips properly?

I have been struggling to customize tooltips using a library called tooltipster. Here is what I currently have: Head of index.html: <head> <!--TOOLTIP CSS--> <link rel="stylesheet" type="type/css" href="node_modules/tooltipster-master ...

Updating a database seamlessly via a dropdown menu without having to refresh the entire webpage

Before we proceed, please take a look at the following code: $(document).ready(function() { $("#alternatecolor [type=button]").each(function() { $(this).on('click', function() { btnObj = $(this); rowId = $(this).attr("rowId") ...

How can a JSON string be assigned to a variable for use in a Google pie chart?

I am currently experiencing an issue with my web server. I am sending a JSON object as an argument via render_template to my website, where I intend to use this data to display a Google pie chart. The problem arises when I try to assign the Google pie cha ...

Obtaining Results from PHP for JSON/AJAX Handling

A colleague shared with me this JavaScript code snippet that could be useful: $.ajax({ type: "POST", url: "../CheckPerson.php", data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','midd ...

Ways to maintain a pointer to a RequireJS module?

Understanding the inner workings of RequireJS has been a bit challenging for me, as the official website doesn't provide clear explanations on fundamental concepts like how to utilize the 'require' and 'define' methods. Currently, ...

What is the process for including a new item in the p-breadcrumb list?

Having trouble getting my code to add a new item to the p-breadcrumb list on click. Any assistance would be greatly appreciated. Thank you in advance! Check out the live demo here ngOnInit() { this.items = [ {label: 'Computer'}, ...

A method for consolidating multiple enum declarations in a single TypeScript file and exporting them under a single statement to avoid direct exposure of individual enums

I am looking to consolidate multiple enums in a single file and export them under one export statement. Then, when I import this unified file in another file, I should be able to access any specific enum as needed. My current setup involves having 2 separ ...

Receiving input in a "textbox" rather than using an alert message

Hey there! I managed to get this jquery code that displays the number of Facebook likes: <script> $.getJSON("https://graph.facebook.com/TuamadreLeggenda?callback=?", function(data) { alert("Likes: " + data.likes); }); </script> Is there ...

Having trouble making changes to FontAwesome CSS using jQuery?

I am currently working on an MVC project where I am using Ajax to update a specific section of a View that contains a FontAwesome 5 icon. The FontAwesome icons are set using CSS classes, so my initial assumption was that it would be simple to remove and ad ...

Execute the script before the Vue.js framework initiates the HTML rendering

In order to determine if the user is logged in or not, and redirect them to the login page if they are not, I am looking for a way to check the user's login status before the HTML (or template) loads. I have attempted to use beforeCreate() and variou ...

Injecting environment variables into webpack configuration

My goal is to set a BACKEND environment variable in order for our VueJS project to communicate with the API hosted there, but I keep receiving an error message saying Unexpected token :. Here is the current code snippet from our config/dev.env.js, and I&a ...

"Unpredictable test failures plaguing my Node.js application with jest and supertest

Recently, I've been working on developing a REST API that accepts a movie title in a POST request to the /movies route. The API then fetches information about that movie from an external API and stores it in a database. Additionally, when you make a P ...

Is concealing content using Javascript or jQuery worth exploring?

While I have been hiding content using display:none; in css, there are concerns that Google may not like this approach. However, due to the needs of jQuery animations, it has been necessary for me. Recently, I have come across a new method for hiding conte ...

Verify if the connection to MongoDB Atlas has been established for MongoDB

When working with MongoDB, I find myself switching between a local database during development and MongoDB Atlas in production. My goal is to implement an efficient text search method that utilizes $search when connected to MongoDB Atlas, and $text when co ...

Searching for text in an HTML table using PHP DOM query

How do I extract text from HTML table cells using PHP DOM query? Here is a sample HTML table: <table> <tr> <th>Job Location:</th> <td><a href="/#">Kabul</a> </td> </tr> <tr> ...

Are you familiar with the Pagination and Card Components offered by Ant Design (antd)?

Can you merge the Pagination feature from antd with Card components to create a layout resembling Pinterest, complete with pagination? The standard Pagination code from https://ant.design/components/pagination/: import { Pagination } from 'antd&apo ...

Dynamic content with Socket.io in Node.js

I am attempting to create a scenario where nodejs triggers an event in an irc chat that causes a html page (Running on *:3000) to execute some JavaScript. However, I am facing an issue where the showDiv(); function is not being executed as expected. Curre ...