Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Setting 'style' attribute of element with object

I saw this in our codebase the other day:

            link.attr('style', map({
                color: '#9a4d9e',
                cursor: 'default'
            }));

map is defined as:

function map(map) {
    var cssValue = [];

    for (var o in map) {
        cssValue.push(o + ':' + map[o] + ';')
    }

    return cssValue.join(';');
}

Is map necessarily? Is there a shorter way to do this?

It's important to note that the "style" attribute overrides any styles set by a class added/defined in the "class" attribute.

like image 350
JamesBrownIsDead Avatar asked May 04 '10 04:05

JamesBrownIsDead


People also ask

How do you change the style of an element using jQuery?

The css() method in JQuery is used to change the style property of the selected element. The css() in JQuery can be used in different ways. Return value: It will return the value of the property for the selected element.

How do you get the value of a style property for an element in a set of matched elements in jQuery?

The jQuery css() methods enables you to get the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


1 Answers

Probably not. A better solution may be to use CSS:

link.css({color: '#9a4d9e',
          cursor: 'default'});

However, .attr('style',) also removes the previous inline style, so it doesn't behave exactly the same.
If you are going to use attr, it's input should be a string, not an object, it isn't specialized to work with the style attribute. an alternative in that case is:

link.attr('style', "color:'#9a4d9e';cursor:'default'");

Seems cleaner in this case. In other cases, your map makes it easier to insert variables into the CSS.
map could have been named better though. It also has an implementation error - it adds double semicolons between attributes: color:red;;cursor:default;

A simple solution to remove the previews style is to call .removeAttr('style') before calling css.

like image 90
Kobi Avatar answered Oct 16 '22 16:10

Kobi