Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove a specific inline style with Javascript|jQuery

I have the following code in my html:

<p id='foo' style='text-align:center; font-size:14pt; font-family:verdana; color:red'>hello world</p> 

and that in my external css:

#foo{ font-size:11pt; font-family:arial; color:#000; } 

I want to remove all font-size and font-family in the style atribute, but not the color and others set in external css.

Result expected:

<p id='foo' style='text-align:center; color:red'>hello world</p> 

Already tried:

$('#foo').removeAttr('style');   // That removes all inline $('#foo').css('font-family',''); // That remove the css setted too 
like image 875
Rafalages Avatar asked Oct 27 '10 12:10

Rafalages


People also ask

How do I remove a single style property in CSS?

Setting the value of a style property to an empty string — e.g. $('#mydiv'). css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's . css() method, or through direct DOM manipulation of the style property.

How do I remove a style tag?

If you want to remove a specific style tag, you can add a class (or id) to it and then use remove() to remove that class.

How do you remove styles in HTML?

Use the removeAttribute() method to remove all styles from an element, e.g. box. removeAttribute('style') . The removeAttribute method will remove the style attribute from the element. Here is the HTML for the examples in this article.

Can inline style be reused?

You cannot reuse the styles anywhere else.


1 Answers

For those that aren't using jQuery, you can delete specific styles from the inline styles using the native removeProperty method. Example:

elem.style.removeProperty('font-family'); 

Of course, IE < 9 doesn't support this so you'll have to use

elem.style.removeAttribute('font-family'); 

so a cross browser way to do it would be:

if (elem.style.removeProperty) {     elem.style.removeProperty('font-family'); } else {     elem.style.removeAttribute('font-family'); } 
like image 97
Ben L Avatar answered Sep 25 '22 09:09

Ben L