Using jQuery, adjust the width of child elements within a container by applying dynamic CSS styling

I am attempting to dynamically set the width of several child elements using jQuery. Here is what I am trying to achieve:

  1. Obtain the count of the desired containers (since there will be multiple instances of the .steps-container class in the DOM)
  2. Iterate through their children
  3. Set the width of their children using the formula: width = 100 / number of children

This is the code I have:

$(document).ready(function() {

    var setStepsWidth = function(stepsContainer) {

        var el = stepsContainer,
            count = stepsContainer.length,
            childrenCount = 0;

        for( var i = 0; i < count; i++ ) {

            childrenCount = el[i].children.length;

            var containerChildren = el[i].children;
            console.log(containerChildren);

            for(var j = 0; j < childrenCount; j++) {

                //test to see if it's working
                childrenCount[j].css('background-color', 'red');

            }

        }
    };

    setStepsWidth($('.steps-container'));

});

When running the code, I encounter an error: "Uncaught TypeError: Cannot read property 'css' of undefined"

What could I be overlooking?

Answer №1

There seems to be an issue with the children property. You should use the function "children()" to retrieve the children. Check out the example below:

$(document).ready(function() {
var setStepsWidth = function(stepsContainer) {

    var el = stepsContainer,
        count = stepsContainer.length,
        childrenCount = 0;

    for( var i = 0; i < count; i++ ) {

        childrenCount = el[i].children().length;

        var containerChildren = el[i].children();
        console.log(containerChildren);


        for(var j = 0; j < childrenCount; j++) {

            //test to see if it's working
            childrenCount[j].css('background-color', 'red');

        }


    }
};

setStepsWidth($('.steps-container'));

});

Alternatively, you can rewrite it like this without using array elements. It may or may not have a performance impact, but here's an alternative approach:

jQuery(document).ready(function() {
    function _stepsWidth(__stepsContainer) {
        jQuery.each(__stepsContainer.children(), function() {
            jQuery(this).css('background-color', 'red');
        });
    }
    _stepsWidth(jQuery('.steps-container'));
});

If you're looking for recursion, you can implement it like this:

jQuery(document).ready(function() {
    function _stepsWidth(__stepsContainer) {
        jQuery.each(__stepsContainer.children(), function() {
            jQuery(this).css('background-color', 'red');
            _stepsWidth(jQuery(this));
        });
    }
    _stepsWidth(jQuery('.steps-container'));
});

Also, if you have multiple containers and want specific styling for each, you can try this:

jQuery(document).ready(function() {
    function _stepsWidth(__stepsContainer) {
        jQuery.each(__stepsContainer.children(), function() {
            jQuery(this).css('background-color', 'red');
        });
    }
    jQuery.each(jQuery('.steps-container'), function() {
        _stepsWidth(jQuery(this));
    });
});

Give it a try and see how it works. :)

Answer №2

You seem to be overcomplicating something that is actually quite straightforward.

  • If you need to loop through the containers, utilize jQuery's .each() method
  • To adjust the width of child elements, take advantage of jQuery's ability to automatically apply changes to all elements in a selection, eliminating the need for manual iteration.
$(document).ready(function() {
    function adjustChildrenWidth($containers) {
        $containers.each(function(i, el) {//loop through the containers
            var $children = $(el).children();//get children within the current container
            $children.width(100 / $children.length);//calculate and apply width to all children in the current container
        });
    }
    adjustChildrenWidth($('.steps-container'));
});

Alternatively, if the child elements are dynamic, consider using an event handler like 'setChildrenWidth' that can be triggered whenever a new child is added or removed.

For instance :

$(document).ready(function() {
    $(document).on('setChildrenWidth', '.steps-container', function() {
        var $children = $(this).children();
        $children.width(100 / $children.length);
    });
});

DEMO

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

Currently, I'm attempting to figure out a way to create a CSS string in my MVC ASP.NET project. Any ideas or suggestions are greatly appreciated

I am currently exploring solutions to generate a CSS string in my ASP.NET MVC Web Application. Specifically, I am interested in creating this at the selector level. For instance, I might have a class named "TableFormat" with the following CSS properties: ...

Stylish Zigzag Border with a Patterned Background

Recently, I've been experimenting with creating a header that features a unique zigzag border. Traditionally, this effect is achieved using images to achieve the desired look. (1) I am curious if there is a way to implement a cross-browser compatible ...

Could you explain the distinction among req.path, req.params, and req.query?

I'm curious about the distinctions among req.path, req.params, req.query, and req.body in node.js. Can someone provide an explanation? ...

Node is looking for a callback function, but instead received something that is undefined

When attempting to build a basic CRUD app in node js, an issue arises with the error message "Route.get() requires a callback function but got a [object Undefined]" specifically on the router.get("/:id", userController.getUser); line. Routes.js const expr ...

Analyze Javascript code and monitor every variable alongside their corresponding values

After watching Bret Victor's engaging talk "Inventing on Principle" the other night, I was inspired to create a real-time JavaScript editor similar to the one he showcased. You can see a glimpse of it in action at 18:05 when he demonstrates binary sea ...

Modify the restriction adjustment upon applying an additional filter

I find myself in a confusing situation and could really use some advice. Here's what's going on: I have the following code to change the default items limit in a module: <form method="get" style="text-align:center;"> <input ...

retrieving data from a php file using ajax for a post request

Utilizing ajax, I have invoked the page search.php: function search(){ var title=$("#search").val(); if(title!=""){ $.ajax({ type:"post", url:"sear ...

Using ng-repeat can cause conflicts with jQuery function calls

I implemented a combination of AngularJS and MaterializeCSS to display images using ng-repeat. MaterializeCSS comes with a jQuery-based materiabox function that triggers an animation to open a modal for each element with the materialbox class. However, I ...

Attempting to extract data from an HTML table and store it in an array using JavaScript with the help of jQuery

Currently, I am faced with a challenge involving extracting values from an HTML table and storing them in a 2-dimensional array using JavaScript. jQuery seems like the ideal solution for this task. While I have managed to get the indices working properly, ...

create the text with double bold - adjusted pages

Is there a method to enhance the boldness of the text without adjusting the font size? Currently, the following styling is applied: numbers: { fontSize: 30, color: '#31C283', fontWeight: 'bold', }, Is there a way to m ...

Jquery Menu featuring subitems aligned to the right

I am experiencing an issue with my drop-down menu in ie6. The subitems menus are shifted to the right, rendering the menu useless. Here is the HTML code: <div id="navigation"> <a href="<?php echo base_url();?>" class="singl ...

Let's explore further - delving into JSON & array manipulation using the foreach loop in Pure JavaScript

Although I have some experience with Java Script, I still consider myself a beginner in certain areas, particularly when it comes to accessing JSON objects and arrays. I've tried various syntax and options for accessing arrays using [], but so far, I ...

Issues with CSS transitions not functioning properly following the use of toggleClass()

I recently implemented a toggle-menu feature, which you can see in action on this demo. To enhance the toggle-menu, I added a CSS transition effect to div.nav-menu, utilizing max-height:0; and increasing it to max-height:480px;. However, after clicking t ...

Confusion surrounding the purpose of an AngularJS controller function

After experimenting with some basic tutorials in AngularJS, I came across a discrepancy in how controllers are declared and used. For instance, in this JSFiddle link - http://jsfiddle.net/dakra/U3pVM/ - the controller is defined as a function name, which w ...

Tips for aligning two divs of varying sizes side by side

Imagine having two div elements: <div id="container"> <div id="left">line one</div> <div id="right">line one<br/>line two</div> </div> Is there a way to have the left and right divs align at the bottom li ...

Is there a way to prevent Angular Material Buttons from overlapping a sticky bar when scrolling?

In my Angular application, I have a navigation bar at the top that sticks in place (position: sticky; top: 0;). Beneath the navigation bar is the content, which includes Angular material components such as mat-buttons or mat-cards. The issue arises when ...

Storing filtered data objects for future use

Introduction to my User Administration Page Currently, I am working on the User Administration page of my project and facing a minor issue. The page includes a table that displays material-ui's Usercard for each user in the system. These cards are ge ...

When using DataTables ajax.reload with pagination enabled, the table content jumps to the bottom of the page

I am currently using jQuery DataTables with ajax sourced data. To ensure that the data remains up to date every 30 seconds without requiring a page refresh, I have been utilizing the ajax.reload() function. To achieve this, I have placed the ajax.reload() ...

A step-by-step guide on utilizing the reduce function to calculate the overall count of a user's GitHub repositories

I need help finding the total number of repositories for a specific user. Take a look at my code below: Javascript const url = "https://api.github.com/users/oyerohabib/repos?per_page=50"; const fetchRepos = async () => { response = await f ...

Is having async as false really detrimental?

Splitting my inquiry into two sections. Within my website, I am dynamically generating some divs by utilizing ajax post requests to retrieve data from the database. Following is the structure of my setup. <html> <body> <script type=" ...