How do you remove an inline CSS style previously applied with jQuery .css()? | A1Lab@FahadM to JavaScriptEnglish • 3 days ago

How do you remove an inline CSS style previously applied with jQuery .css()?

message-square
0

To remove an inline CSS style previously applied with jQuery .css(), pass an empty string ("") (or null) as the property value—such as $el.css("color", "") or $el.css("background-color", "")—which instructs jQuery to clear that inline property from the element’s style attribute so stylesheet rules or defaults take over again; if you want to wipe all inline styles on the element at once, use $el.removeAttr("style") (or native el.style.removeProperty("...")).


1. Removing a Single Inline Property with .css(prop, "")

Pass "" as the second argument to .css(propertyName, "") (or pass an object with "" values for multiple properties) to remove inline declarations without stripping other inline styles or classes:

// Remove one or more inline CSS properties set via jQuery .css()
function clearInlineCssProperties($target, properties) {
  if (typeof $ === "undefined" || !$target || $target.length === 0) {
    throw new TypeError("Expected a non-empty jQuery collection as $target.");
  }
  if (!Array.isArray(properties) || properties.length === 0) {
    throw new TypeError("Expected properties to be a non-empty array of CSS property names.");
  }

  try {
    const clearedMap = new Map();
    for (const prop of properties) {
      if (typeof prop !== "string" || prop.trim().length === 0) {
        throw new TypeError("Each CSS property name must be a non-empty string.");
      }
      const cleanProp = prop.trim();
      $target.css(cleanProp, "");
      clearedMap.set(cleanProp, "");
    }
    return clearedMap;
  } catch (error) {
    throw new Error(`Failed to clear inline CSS properties: ${error.message}`);
  }
}

// Example usage:
// const $card = $("#profile-card");
// $card.css({ "border-color": "red", "padding-top": "24px" });
// clearInlineCssProperties($card, ["border-color", "padding-top"]);
  • Use "" rather than undefined: Passing undefined as the second argument to .css(prop, undefined) is a no-op in jQuery and will not remove the style.
  • Prefer CSS classes over .css() for stateful UI: Toggling classes (.addClass() / .removeClass()) keeps styling rules in CSS rather than scattering inline styles across JS.

2. Clearing All Inline Styles or Custom / Vendor Properties Safely

When resetting an entire inline style attribute or clearing custom properties (--custom-var) and vendor prefixes, combine .removeAttr("style") or native style.removeProperty() with defensive existence checks:

// Remove all inline styles or a specific CSS custom property across matched elements
function resetElementInlineStyles($target, { removeAll = true, customProperties = [] } = {}) {
  if (typeof $ === "undefined" || !$target || $target.length === 0) {
    throw new TypeError("Expected a non-empty jQuery collection as $target.");
  }

  try {
    if (removeAll) {
      $target.removeAttr("style");
    }

    if (Array.isArray(customProperties)) {
      for (const varName of customProperties) {
        if (typeof varName === "string" && varName.trim().length > 0) {
          $target.each((_, el) => {
            if (el && el.style && typeof el.style.removeProperty === "function") {
              el.style.removeProperty(varName.trim());
            }
          });
        }
      }
    }

    return $target.length;
  } catch (error) {
    throw new Error(`Failed to reset inline styles: ${error.message}`);
  }
}

// Example usage:
// resetElementInlineStyles($("#modal-panel"), { removeAll: true });
  • .removeAttr("style") removes the entire style="..." attribute: Useful when resetting an element back to clean stylesheet control after dynamic inline styling.
  • Remember .css() only clears inline style declarations: It does not remove rules coming from external stylesheets, <style> blocks, or class selectors.

3. Native DOM Equivalent (element.style.removeProperty)

In modern vanilla JavaScript without jQuery, element.style.removeProperty("background-color") removes an inline property directly (and element.style.setProperty("--accent", "") or removeProperty("--accent") clears CSS variables):

// Native DOM helper to remove a single inline style property without jQuery
function removeInlineStyleNative(element, propertyName) {
  if (!(element instanceof Element) || !element.style) {
    throw new TypeError("Expected element to be a DOM Element with a style declaration.");
  }
  if (typeof propertyName !== "string" || propertyName.trim().length === 0) {
    throw new TypeError("Expected propertyName to be a non-empty string.");
  }

  try {
    return element.style.removeProperty(propertyName.trim());
  } catch (error) {
    throw new Error(`Failed to remove inline property "${propertyName}": ${error.message}`);
  }
}

// Example usage:
// const box = document.querySelector("#status-box");
// if (box) {
//   box.style.color = "crimson";
//   removeInlineStyleNative(box, "color");
// }
  • Use kebab-case ("background-color") with removeProperty(): Matches standard CSS property syntax cleanly.
  • Guard against missing elements (null): Always check if (box) before touching .style to avoid runtime TypeErrors.