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/
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).
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.
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.
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: $().
Replace:
$("#spanText").attr("css", { backgroundColor: "gray" });
with
$("#spanText").attr('style', 'background-color:gray');
Probably, it was meant to be
$("#spanText").attr('style', 'background-color:gray');
This may work, but has some problems:
style
property instead of style
attribute.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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With