Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery attr() to set “css”

Tags:

jquery

css

attr

I am reading the book "jQuery Pocket Reference", O’Reilly, 2011.

On page 15 it says:

'For example, calling attr("css", {backgroundColor:"gray"}) is the same as calling css({backgroundColor:"gray"}).'

But I cannot make the attr(“css”, { }) work. My test code: http://jsfiddle.net/4UMN3/4/

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

 });

});

The css() method works fine, http://jsfiddle.net/4UMN3/5/

like image 222
user3026964 Avatar asked Jul 10 '14 22:07

user3026964


People also ask

Can I use ATTR CSS?

While attr() is supported for effectively all browsers for the content property, CSS Values and Units Level 5 adds the ability to use attr() on any CSS property, and to use it for non-string values (e.g. numbers, colors).

What is the use of attr () method in jQuery?

jQuery attr() Method The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element.

How do I get attr in CSS?

The attr() CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.

Can we change CSS property using JavaScript and jQuery?

It is possible to change the CSS property of an element by using a simple JavaScript API, but we try to complete this challenge using jQuery css() method. Syntax: $().


2 Answers

Replace:

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

with

$("#spanText").attr('style',  'background-color:gray');
like image 137
Branimir Đurek Avatar answered Sep 19 '22 13:09

Branimir Đurek


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';
like image 29
Oriol Avatar answered Sep 21 '22 13:09

Oriol