Using jQuery attr() to set “css”

Probably, it was meant to be

$("#spanText").attr('style', 'background-color:gray');

This may work, but has some problems:

  • It is preferred to change style property instead of style attribute.
  • It will replace all previously set inline styles.

Then, if you use jQuery, better use css method:

$("#spanText").css('background-color', 'gray');

But style property is useful in vanilla-js:

document.getElementById("spanText").style.backgroundColor = 'gray';

Replace:

$("#spanText").attr("css", { backgroundColor: "gray" });

with

$("#spanText").attr('style',  'background-color:gray');

Tags:

Css

Jquery

Attr