Evan
Evan

Reputation: 3501

Remove specific inline style with jquery

There's an asp menu I'm using that is auto inserting style="width:3px;" into my menu table tds creating a nasty gab in between my tabs. I'm testing to remove this inline style with jquery instead of our developer customizing the menu just for this cosmetic blemish.

below is a simple example:

<table border="1" cellspacing="0" cellpadding="0">
   <tr>
      <td style="width:3px;">hello world</td>
   </tr>
</table>

in jquery, i can remove all tds with the style attribute by doing:

$('td').removeAttr('style');

so, my question is, how can i target the inline style that only contains 3px?

Here's my live demo: http://jsfiddle.net/n9upF/

Upvotes: 6

Views: 22671

Answers (3)

Nik Chankov
Nik Chankov

Reputation: 6047

I believe that Evan wanted to remove only the width:3px; from the style while the other css styling remain in the attribute. So here is the solution:

$('td').each(function(){
  if ($(this).attr('style').indexOf('3px') !== -1){
    var style = $(this).attr('style');
      $(this).attr('style', style.replace(/width: ?3px;/g, ''));
  }
});

Working example is here

If this is not what you needed then the Sarfraz is shown the proper solution. :)

Upvotes: 8

Brian Kim
Brian Kim

Reputation: 25346

You are asking how you can select td's that have style attribute with only width:3px; in it, right?

You can use Attribute Equals Selector.

$("td[style='width:3px;']").removeAttr("style");​

Upvotes: 10

Sarfraz
Sarfraz

Reputation: 382676

so, my question is, how can i only target the inline style that contains only 3px?

Try this:

$('td').each(function(){
  if ($(this).attr('style').indexOf('3px') !== -1){
    $(this).removeAttr('style');
  }
});

See Working Example

Upvotes: 4

Related Questions