How to Change an HTML Element’s Style Using jQuery – The Right Way

//

user

There was a time I wanted to change the style of an HTML element using jQuery.
Simple task, right? But I quickly realized there’s a wrong way and a right way to do it.

Let me show you what I learned.


The Wrong Way: Using .attr("style", ...)

At first, I tried this:

$('#ID').attr("style", "background-color: #f0ffff");

Yes—it works.
The background color changes to light cyan (#f0ffff). ✅

BUT… if the element previously had other style properties like widthheight, or margin, they’re gone. Just wiped out. ❌

Why?
Because .attr("style", "...") overwrites the entire style attribute. You’re replacing everything that was there.


The Right Way: Using .css("property", "value")

Then I switched to this:

$('#ID').css("background", "#f0ffff");

Boom! Background color changed—and the original styles like widthheight, etc. stayed untouched. 🙌

That’s because .css() only sets or updates a specific style property.


Example

Let’s say you have this element:

<div id="box" style="width: 100px; height: 100px; background: #fff;"></div>

With .attr():

$('#box').attr("style", "background-color: #f0ffff");

Result:

<div id="box" style="background-color: #f0ffff;"></div> <!-- width and height are gone! -->

With .css():

$('#box').css("background-color", "#f0ffff");

Result:

<div id="box" style="width: 100px; height: 100px; background-color: #f0ffff;"></div>

Much better.


Final Thoughts

  • Use .attr("style", "...") only if you want to replace all styles (which is rare).
  • Use .css() when you want to change just one or two properties without affecting the rest.
  • You can also pass an object to .css() to change multiple properties at once:$('#box').css({ "background-color": "#f0ffff", "border": "1px solid #ccc" });

Lesson learned: .css() is your best friend for clean, targeted style updates with jQuery. 😄

Leave a Comment