user2395853
user2395853

Reputation: 89

How to change the width for all elements given a specific class?

I need to change the width of all div elements with a specific class. For example:

<div class="grid1 first">
<div class="grid2">
<div class="grid3">
<div class="grid4 last">

All the DIVs have initial width of 23%. DIVs with "first" or "last" class need to have additional 1% width. I tried with this code:

var addwidth = 0;
$("[class^=grid]").each(function() {
   if ($(this).hasClass("first") || $(this).hasClass("last")) {
       addwidth += $(this).width() + 1 + "%";
       $(this).width(addwidth);
   }
});

Thank you.

Upvotes: 2

Views: 1844

Answers (5)

lashab
lashab

Reputation: 186

$('[class^="grid"]').each(function(i,element){
    if ( $(element).is('.first') || $(element).is('.last') ) {
    var width = ( 100 * parseFloat($(element).css('width')) / parseFloat($(element).parent().css('width')) ) + 1 + '%'
      $(element).css('width',width);
    }
})

Upvotes: 0

colestrode
colestrode

Reputation: 10668

You can do this with CSS if you don't need dynamic widths:

.first, .last {
    width: 24%;
}

You can calculate the widths dynamically, though you'll have to work around the fact that jQuery's width() and css() methods will return the width in pixels. To do this, you can get the width of the parent and calculate the percentage this child occupies, then update that value and set the child's width:

$(".first, .last").each(function () {
    var that = $(this),
        parentWidth = that.parent().width(),
        width = that.width(),
        percentage = parseInt((width/parentWidth)*100, 10)
    ;

    that.css("width", (percentage + 1) + '%');
});

Working Demo

Upvotes: 2

Renish Khunt
Renish Khunt

Reputation: 5824

You can also used that code like

$(.last).css('width',(23+1)+'%');

Upvotes: 0

Nishu Tayal
Nishu Tayal

Reputation: 20860

You might have set the initial width "23%" in css .
In your code you are doing concatenation of integer and string, that wont work so split that code in two lines as below.

var addwidth = 0;
$("[class^=grid]").each(function() {
   if ($(this).hasClass("first") || $(this).hasClass("last")) {
       addwidth = parseInt($(this).css('width')) + 1;
       console.log(addwidth);
       $(this).css('width',addwidth+"%");
   }
});

Upvotes: 0

Jonny Sooter
Jonny Sooter

Reputation: 2417

Replace this:

addwidth += $(this).width() + 1 + "%";
$(this).width(addwidth);

With this:

addwidth += $(this).width() + 1;
$(this).width(addwidth + "%");

Upvotes: 0

Related Questions