Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the style value using attr

My HTML CODE HERE:

 <i id="bgcolor" style="background-color: rgb(255, 146, 180)"></i>

I want to get the background-color value using jquery attr. What i tried is below:

$("#bgcolor").mouseleave(function(){
        var bodyColor = $(this).attr("style");

        $("body").css(bodyColor);
    });

But this output is:

background-color: rgb(255, 146, 180);

And now that I've added it to my css it will not work. How can I achieve this task?

enter image description here

like image 283
Dilini Wasana Avatar asked May 14 '13 17:05

Dilini Wasana


People also ask

How do I find my ATTR value?

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. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.

How do you find the style of an element?

First, you need to select the element with querySelector . Then, you use getComputedStyle to get the element's styles. If you log style , you should see an object that contains every CSS property and their respective values. You can also see this object in Chrome's and Firefox's dev tools.

What is 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.


2 Answers

Check out the documentation for .css: http://api.jquery.com/css/

var bodyColor = $(this).css("backgroundColor");
like image 183
dwaddell Avatar answered Sep 28 '22 06:09

dwaddell


This is what you are looking for(this code works):

$("#bgcolor").mouseleave(function(){
    var bodyColor = $(this).attr("style");
    $("body").attr("style", bodyColor);
});

But, instead of using attr you should use css, so the code will be:

$("#bgcolor").mouseleave(function(){
    var bodyColor = $(this).css("background-color");
    $("body").css("background-color", bodyColor);
});

JSFiddle

like image 41
Niccolò Campolungo Avatar answered Sep 28 '22 07:09

Niccolò Campolungo