Search code examples
jquerymaxwidth

How to retrieve the maximum width of multiple <input> elements with the same class using jQuery?


I have five input elements with different widths, but all of them share the same class, for example, class="c1".

I am looking for a way to use jQuery to retrieve the maximum width among them. Can anyone suggest a solution? Thank you.


Solution

  • You can achieve this by looping through each element and checking for each element's width is greater than the next one and storing the maximum width in a variable to make sure that the current width is greater than the previous. Here's an example code snippet that should work

    let maxWidth = 0;
    $('.c1').each(function() {
        const elWidth = $(this).width();
        if(elWidth > maxWidth){
            maxWidth = elWidth;
        }
    });
    console.log('Max width', maxWidth)
    

    Hope you find this useful :)