Cómo aplicar!uso importante.css ()?


Estoy teniendo problemas para aplicar un estilo que es !important. He intentado:

$("#elem").css("width", "100px !important");

Esto no hace nada; no se aplica ningún estilo de ancho. ¿Hay una forma jQuery-ish de aplicar tal estilo sin tener que sobrescribir cssText (lo que significaría que tendría que analizarlo primero, etc.)?

Editar : Debo agregar que tengo una hoja de estilos con un estilo !important que estoy tratando de reemplazar con un estilo !important en línea, por lo que usar .width() y similares no funciona ya que obtiene anulado por mi estilo externo !important.

Además, el valor que anulará el valor anterior se calcula, por lo que no puedo simplemente crear otro estilo externo.

Author: miken32, 2010-04-17

30 answers

Creo que he encontrado una solución real. Lo he convertido en una nueva función:

jQuery.style(name, value, priority);

Puede usarlo para obtener valores con .style('name') al igual que .css('name'), obtener la declaración de CSSStyleDeclaration con .style() y también establecer valores, con la capacidad de especificar la prioridad como 'importante'. Véase este .

Demo

var div = $('someDiv');
console.log(div.style('color'));
div.style('color', 'red');
console.log(div.style('color'));
div.style('color', 'blue', 'important');
console.log(div.style('color'));
console.log(div.style().getPropertyPriority('color'));

Aquí está la salida:

null
red
blue
important

La Función

(function($) {    
  if ($.fn.style) {
    return;
  }

  // Escape regex chars with \
  var escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  };

  // For those who need them (< IE 9), add support for CSS functions
  var isStyleFuncSupported = !!CSSStyleDeclaration.prototype.getPropertyValue;
  if (!isStyleFuncSupported) {
    CSSStyleDeclaration.prototype.getPropertyValue = function(a) {
      return this.getAttribute(a);
    };
    CSSStyleDeclaration.prototype.setProperty = function(styleName, value, priority) {
      this.setAttribute(styleName, value);
      var priority = typeof priority != 'undefined' ? priority : '';
      if (priority != '') {
        // Add priority manually
        var rule = new RegExp(escape(styleName) + '\\s*:\\s*' + escape(value) +
            '(\\s*;)?', 'gmi');
        this.cssText =
            this.cssText.replace(rule, styleName + ': ' + value + ' !' + priority + ';');
      }
    };
    CSSStyleDeclaration.prototype.removeProperty = function(a) {
      return this.removeAttribute(a);
    };
    CSSStyleDeclaration.prototype.getPropertyPriority = function(styleName) {
      var rule = new RegExp(escape(styleName) + '\\s*:\\s*[^\\s]*\\s*!important(\\s*;)?',
          'gmi');
      return rule.test(this.cssText) ? 'important' : '';
    }
  }

  // The style function
  $.fn.style = function(styleName, value, priority) {
    // DOM node
    var node = this.get(0);
    // Ensure we have a DOM node
    if (typeof node == 'undefined') {
      return this;
    }
    // CSSStyleDeclaration
    var style = this.get(0).style;
    // Getter/Setter
    if (typeof styleName != 'undefined') {
      if (typeof value != 'undefined') {
        // Set style property
        priority = typeof priority != 'undefined' ? priority : '';
        style.setProperty(styleName, value, priority);
        return this;
      } else {
        // Get style property
        return style.getPropertyValue(styleName);
      }
    } else {
      // Get CSSStyleDeclaration
      return style;
    }
  };
})(jQuery);

Vea este para ejemplos de cómo leer y establecer los valores CSS. Mi problema era que ya había establecido !important para el ancho en mi CSS para evitar conflictos con el CSS de otro tema, pero cualquier cambio que hiciera en el ancho en jQuery no se vería afectado ya que se agregarían al atributo style.

Compatibilidad

Para establecer la prioridad usando la función setProperty, Este artículo dice que hay soporte para IE 9+ y todos los demás navegadores. He intentado con IE 8 y ha fallado, por lo que construí soporte para él en mis funciones (ver arriba). Se funcionará en todos los demás navegadores usando setProperty, pero necesitará mi código personalizado para funcionar en

 296
Author: Aram Kocharyan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-06 18:59:24

El problema se debe a que jQuery no entiende el atributo !important y, como tal, no puede aplicar la regla.

Es posible que pueda solucionar ese problema y aplicar la regla refiriéndose a él, a través de addClass():

.importantRule { width: 100px !important; }

$('#elem').addClass('importantRule');

O usando attr():

$('#elem').attr('style', 'width: 100px !important');

Sin embargo, este último enfoque eliminaría cualquier regla de estilo en línea previamente establecida. Así que úsalo con cuidado.

Por supuesto, hay un buen argumento de que el método de @Nick Craver es más fácil/sabio.

Lo anterior, attr() enfoque modificado ligeramente para preservar la cadena/propiedades original style:

$('#elem').attr('style', function(i,s) { return s + 'width: 100px !important;' });
 526
Author: David Thomas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-12 15:15:31

Puede establecer el ancho directamente usando .width() así:

$("#elem").width(100);

Actualizado para comentarios: También tienes esta opción, pero reemplazará todo css en el elemento, así que no estoy seguro de que sea más viable:

$('#elem').css('cssText', 'width: 100px !important');
 136
Author: Nick Craver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-16 21:22:50
var elem = $("#elem");
elem[0].style.removeAttribute('width');
elem[0].style.setProperty('width', '100px', 'important');
 65
Author: BettaSplendens,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-13 18:18:29

La respuesta de David Thomas describe una forma de usar $('#elem').attr('style', …), pero advierte que usarlo eliminará estilos previamente establecidos en el atributo style. Aquí hay una forma de usar attr() sin ese problema:

var $elem = $('#elem');
$elem.attr('style', $elem.attr('style') + '; ' + 'width: 100px !important');

Como una función:

function addStyleAttribute($element, styleAttribute) {
    $element.attr('style', $element.attr('style') + '; ' + styleAttribute);
}
addStyleAttribute($('#elem'), 'width: 100px !important');

Aquí hay un JS Bin demo.

 51
Author: Rory O'Kane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:34

Después de leer otras respuestas y experimentar, esto es lo que funciona para mí:

$(".selector")[0].style.setProperty( 'style', 'value', 'important' );

Esto no funciona en IE 8 y bajo, sin embargo.

 27
Author: Nate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-02 23:33:39

Puedes hacer esto:

$("#elem").css("cssText", "width: 100px !important;");

Usando "cssText" como el nombre de la propiedad y lo que quieras agregar al CSS como su valor.

 22
Author: hawkeye126,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:31:09

Puedes lograr esto de dos maneras:

$("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
$("#elem").attr("style", "width: 100px !important");
 17
Author: kva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-05 04:11:49

No hay necesidad de ir a la complejidad de la respuesta de @AramKocharyan, ni la necesidad de insertar etiquetas de estilo dinámicamente.

Simplemente sobrescribir el estilo, pero no tienes que analizar nada, ¿por qué lo harías?

// Accepts the hyphenated versions (i.e. not 'cssFloat')
function addStyle(element, property, value, important) {
    // Remove previously defined property
    if (element.style.setProperty)
        element.style.setProperty(property, '');
    else
        element.style.setAttribute(property, '');

    // Insert the new style with all the old rules
    element.setAttribute('style', element.style.cssText +
        property + ':' + value + ((important) ? ' !important' : '') + ';');
}

No se puede usar removeProperty(), porque no eliminará las reglas !important en Chrome.
No se puede usar element.style[property] = '', porque solo acepta camelCase en Firefox.

Probablemente podría acortar esto con jQuery, pero esta función vanilla se ejecutará en navegadores modernos, Internet Explorer 8, etc.

 14
Author: Hashbrown,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:30:07

Esto es lo que hice después de encontrar este problema...

var origStyleContent = jQuery('#logo-example').attr('style');
jQuery('#logo-example').attr('style', origStyleContent + ';width:150px !important');
 12
Author: kebyang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:27:15

Esta solución no anula ninguno de los estilos anteriores, solo aplica el que necesita:

var heightStyle = "height: 500px !important";
if ($("foo").attr('style')) {
  $("foo").attr('style', heightStyle + $("foo").attr('style').replace(/^height: [-,!,0-9,a-z, A-Z, ]*;/,''));
else {
  $("foo").attr('style', heightStyle);
}
 9
Author: Alain Beauvois,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-05 13:44:39

Si no es tan relevante y ya que está tratando con un elemento que es #elem, puede cambiar su id a otra cosa y darle el estilo que desee...

$('#elem').attr('id', 'cheaterId');

Y en tu CSS:

#cheaterId { width: 100px;}
 9
Author: Sinan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:25:11

La solución más fácil y mejor para este problema de mi parte fue simplemente usar addClass() en lugar de .css () or .attr().

Por ejemplo:

$('#elem').addClass('importantClass');

Y en tu archivo CSS:

.importantClass {
    width: 100px !important;
}
 9
Author: Jack Fairfield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:32:31

En lugar de usar la función css() intente con la función addClass():

  <script>
  $(document).ready(function() {
    $("#example").addClass("exampleClass");
  });
  </script>

  <style>
  .exampleClass{
    width:100% !important;
    height:100% !important;
  }
  </style>
 8
Author: user3778043,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-24 09:15:05

Para tu información, no funciona porque jQuery no lo soporta. Había una multa presentada en 2012 (#11173 $(elem).css("propiedad", "valor !importante") falla ) que finalmente se cerró como WONTFIX.

 6
Author: Álvaro González,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-16 15:59:40

Primero necesitamos eliminar el estilo anterior. Lo elimino usando una expresión regular. Aquí hay un ejemplo para cambiar de color:

var SetCssColorImportant = function (jDom, color) {
       var style = jDom.attr('style');
       style = style.replace(/color: .* !important;/g, '');
       jDom.css('cssText', 'color: ' + color + ' !important;' + style); }
 6
Author: Rodrigo Perez Burgues,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:26:17

Una forma alternativa de añadir estilo en head:

$('head').append('<style> #elm{width:150px !important} </style>');

Esto añade estilo después de todos sus archivos CSS por lo que tendrá mayor prioridad que otros archivos CSS y se aplicará.

 6
Author: h0mayun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:27:48

Puede ser que se vea así:

Cache

var node = $('.selector')[0];
OR
var node = document.querySelector('.selector');

Establecer CSS

node.style.setProperty('width', '100px', 'important');

Eliminar CSS

node.style.removeProperty('width');
OR
node.style.width = '';
 6
Author: SerzN1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:31:57

Asumiría que lo probaste sin agregar !important?

El CSS en línea (que es como JavaScript agrega estilo) anula el CSS de la hoja de estilos. Estoy bastante seguro de que ese es el caso incluso cuando la regla CSS de la hoja de estilos tiene !important.

Otra pregunta (tal vez una pregunta estúpida, pero debe hacerse.): ¿Es el elemento en el que estás tratando de trabajar display:block; o display:inline-block;?

No conoce su experiencia en CSS... los elementos en línea no siempre se comportan como cabría esperar.

 4
Author: Dave Gregory,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:24:18

Hazlo así:

$("#elem").get(0).style.width= "100px!important";
 4
Author: user217447,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:28:23

Puede o no ser apropiado para su situación, pero puede usar selectores CSS para muchas de este tipo de situaciones.

Si, por ejemplo, quería de la 3a y 6a instancias de .cssText para tener un ancho diferente se puede escribir:

.cssText:nth-of-type(3), .cssText:nth-of-type(6) {width:100px !important;}

O:

.container:nth-of-type(3).cssText, .container:nth-of-type(6).cssText {width:100px !important;}
 3
Author: Tim Cutting,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-30 12:35:57

Creo que funciona bien y puede sobrescribir cualquier otro CSS anterior (este elemento: DOM):

this.setAttribute('style', 'padding:2px !important');
 3
Author: nobjta_9x_tq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:39:44

También descubrí que ciertos elementos o complementos (como Bootstrap) tienen algunos casos de clases especiales donde no juegan bien con !important u otras soluciones como .addClass/.removeClass, y por lo tanto tienes que activarlos/desactivarlos.

Por ejemplo, si usas algo como <table class="table-hover"> la única manera de modificar con éxito elementos como colores de filas es activar/desactivar la clase table-hover, de esta manera

$(your_element).closest("table").toggleClass("table-hover");

¡Esperemos que esta solución sea útil para alguien! :)

 2
Author: Austin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-02 20:31:13

Podemos usar setProperty o cssText para agregar !important a un elemento DOM usando JavaScript.

Ejemplo 1:

elem.style.setProperty ("color", "green", "important");

Ejemplo 2:

elem.style.cssText='color: red !important;'
 2
Author: VISHNU Radhakrishnan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:33:41

Tuve el mismo problema al intentar cambiar un color de texto de un elemento de menú cuando "evento". La mejor manera que encontré cuando tuve este mismo problema fue:

Primer paso: Cree, en su CSS, una nueva clase con este propósito, por ejemplo:

.colorw{ color: white !important;}

Último paso: Aplique esta clase usando el método addClass de la siguiente manera:

$('.menu-item>a').addClass('colorw');

Problema resuelto.

 2
Author: JoelBonetR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:34:37

Tres ejemplos de trabajo

Tuve una situación similar, pero usé .find () después de luchar con .más cercano () durante mucho tiempo con muchas variaciones.

El Código de Ejemplo

// Allows contain functions to work, ignores case sensitivity

jQuery.expr[':'].contains = function(obj, index, meta, stack) {
    result = false;
    theList = meta[3].split("','");
    var contents = (obj.textContent || obj.innerText || jQuery(obj).text() || '')
    for (x=0; x<theList.length; x++) {
        if (contents.toLowerCase().indexOf(theList[x].toLowerCase()) >= 0) {
            return true;
        }
    }
    return false;
};

$(document).ready(function() {
    var refreshId = setInterval( function() {
        $("#out:contains('foo', 'test456')").find(".inner").css('width', '50px', 'important');
    }, 1000); // Rescans every 1000 ms
});

Alternativa

$('.inner').each(function () {
    this.style.setProperty('height', '50px', 'important');
});

$('#out').find('.inner').css({ 'height': '50px'});

Trabajando: http://jsfiddle.net/fx4mbp6c /

 2
Author: computerguy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:38:47

Esta solución dejará todo el javascript computado y agregará la etiqueta importante en el elemento: Puede hacer (por ejemplo, si necesita establecer el ancho con la etiqueta importante)

$('exampleDiv').css('width', '');
//This will remove the width of the item
var styles = $('exampleDiv').attr('style');
//This will contain all styles in your item
//ex: height:auto; display:block;
styles += 'width: 200px !important;'
//This will add the width to the previous styles
//ex: height:auto; display:block; width: 200px !important;
$('exampleDiv').attr('style', styles);
//This will add all previous styles to your item
 2
Author: Sebastian Leandro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-19 17:40:19

Https://jsfiddle.net/xk6Ut/256 /

Un enfoque alternativo es crear y actualizar dinámicamente la clase CSS en JavaScript. Para ello, podemos utilizar el elemento style y necesitamos emplear el ID del elemento style para poder actualizar la clase CSS

function writeStyles(styleName, cssText) {
    var styleElement = document.getElementById(styleName);
    if (styleElement) document.getElementsByTagName('head')[0].removeChild(
        styleElement);
    styleElement = document.createElement('style');
    styleElement.type = 'text/css';
    styleElement.id = styleName;
    styleElement.innerHTML = cssText;
    document.getElementsByTagName('head')[0].appendChild(styleElement);
}

...

  var cssText = '.testDIV{ height:' + height + 'px !important; }';
  writeStyles('styles_js', cssText)
 1
Author: Razan Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-26 00:54:15

La solución más segura para esto es agregar una clase y luego hacer la magia en CSS :-), addClass() y removeClass() deberían hacer el trabajo.

 1
Author: Ryan S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-29 09:40:05

Otro método fácil para resolver este problema añadiendo el atributo style:

$('.selector').attr('style', 'width:500px !important');
 -6
Author: user3556813,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-21 15:41:01