views:

15

answers:

3

Hi,

I select some tables using this:

$('.StatusDateTable').each(function() {
var statusLight = $(this).find(".StatusLight").attr("src");
statusLight = statusLight.substring(33).slice(0,-9);

if (statusLight == "Blue") {
    var columns = Math.abs((start - end)-1);
    var columnWidth = 40;
    var marginRight = Math.abs(columnWidth * columns);

Now I want to set margin-right="theValueOfmarginRightHere" on the current table, is this possible?

I tried something like:

$(this).attr('margin-right=" + marginRight + "');

but obviously it doesn't work.

Thanks in advance.

A: 
$(this).css({marginRight:marginRight})
aularon
A: 

$(this).css('marginRight',marginRight + 'px');

Moin Zaman
A: 

Use .css():

$(this).css('margin-right', marginRight);

You might have to add px at the end, not sure about this: marginRight + 'px'.

Comments on your code line:

  • margin-right is no attribute of an HTML element. It is a CSS property. So you cannot set such properties with the attr() method.
  • Have a look at attr() which parameters the method expects. It is either:
    • attr(name) to get the attribute value.
    • attr(name, value) to set the value. You don't have to create a string like name=value.
  • When you do string concatenation, you have to be careful with mixing ' and ". Yours would indeed create the string margin-right=" + marginRight + " (as you can see from the syntax highlighter). To concatenate the right way, you have to put single quotes at the right spot:

    'margin-right="' + marginRight + '"'
    //           --^               --^
    

    `

Felix Kling
thanks for the comments
Peter