1

I want to set margin 0, padding 0 but it not working. Other style is working

$('#mofiz tbody tr td').each(function () {
    $(this).css("padding", "0 !important");
    $(this).css("margin", "0 !important");
    $(this).css("color", "blue");
    $(this).css("background", "white");
});
Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57
  • Are you using any framework? like bootstrap? – Raeesh Alam Sep 30 '20 at 10:30
  • You can't set `!important` on an inline style. A far better approach is to put the necessary rules in a class (with high enough specificity so you don't need the `!important` flag at all, as it's not good practice to use it), then you can use `addClass()` in your JS – Rory McCrossan Sep 30 '20 at 10:33
  • 1
    Check this link: https://stackoverflow.com/a/2655976/1966247 – Muhammad Sep 30 '20 at 10:38
  • $(this).addClass('padMarginImportant'); color, background working fine but padding and margin not working in this way – Tariqul Islam Sep 30 '20 at 11:04

2 Answers2

2

You can define more style properties in single initialization method like .css({...}).
I define table td{ padding:10px} but its override by .css({}) method.

$('#mofiz tbody tr td').css({
  padding: 0,
  margin: 0,
  color: "blue",
  background: "white"
});
table td{
  padding: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellpadding="0" cellspacing="0" border="1" id="mofiz">
  <tbody>
    <tr>
      <td>Row#1 Col#1</td>
      <td>Row#1 Col#2</td>
      <td>Row#1 Col#3</td>
    </tr>
    <tr>
      <td>Row#2 Col#1</td>
      <td>Row#2 Col#2</td>
      <td>Row#2 Col#3</td>
    </tr>
    <tr>
      <td>Row#3 Col#1</td>
      <td>Row#4 Col#2</td>
      <td>Row#5 Col#3</td>
    </tr>
  </tbody>
</table>
Raeesh Alam
  • 3,380
  • 1
  • 10
  • 9
1

You can not apply the !important rule using .css()

Use cssText instead

$(this).css("cssText", "padding: 0 !important");

$('div').css("cssText", "padding: 0 !important;margin: 0 !important");
$('div').css("color", "blue");
$('div').css("background", "white");

console.log('Padding : ' + $('div')[0].style.padding)
console.log('Margin : ' + $('div')[0].style.margin)
console.log('Color : ' + $('div')[0].style.color)
console.log('Background : ' + $('div')[0].style.background)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>

<div>This is a test</div>

https://jsfiddle.net/o1mqx6y7/

Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57