views:

81

answers:

3

I need to copy a class data to a div, but without setting class name or with other class name.

for instance:

$('#blabla').addClass('xxx');

And then remove the class name but leaving the style data. The thing is that I need to set the style information but I can't set the class name because It gets conflicted with some other code.

A: 

Depending on what styles you're trying to apply, it may work to do the following:

  1. addClass()
  2. Get the CSS properties from your element and apply them using the css() method
  3. removeClass()

Code:

var blabla = $('#blabla');
blabla.addClass('xxx');
blabla.css({
    fontWeight: blabla.css('fontWeight'),
    display: blabla.css('display'),
    float: blabla.css('float'),
});
blabla.removeClass('xxx');
Pat
Thank you, but I don't really know the css properties, and It can change because the class is part of the JQuery UI theme. Could I use the "each" iterator?
Santiago
A: 

You could loop through all computed styles for that element and apply them in a style attribute, then remove the class name. Or perhaps parse the CSS rules and apply the styles from .xxx that way.

You can loop through all CSS properties like this:

var elem = $('#blabla')[0],list = {},props;
if (document.defaultView && document.defaultView.getComputedStyle) {
    props = document.defaultView.getComputedStyle(elem, "");
    $.each(props, function(i, prop) {
        list[prop] = props.getPropertyValue(prop);
    });
} else if (elem.currentStyle) { // IE
    props = elem.currentStyle;
    $.each(props, function(prop, val) {
        list[prop] = val;
    });
}

console.log(list) // the entire computed style object

If you do this you will also get all the inherited and computed styles, even from the browser CSS.

David
It seemed the solution but I don't know how to do it... I'll try it
Santiago
+1  A: 

Use getComputedStyle to get all styles applied to the object. Note that this may be a really big list.

var sourceDiv = $('#source');
var targetDiv = $('#target');

// IE 6,7,8 doesn't support this. Google how to make this cross-browser
var styles = window.getComputedStyle(sourceDiv.get(0), null);
var property, value;

for(var i = 0; i < styles.length; i++) {
    name = styles[i];
    value = sourceDiv.css(name);
    targetDiv.css(name, value);
}

This shows me 207 properties for each element on Chrome. If you are applying this to a lot of elements, it may slow things down. A faster approach in that case would be to tap directly into the CSS rules and styles declared by jQuery UI, and manipulate only the styles declared in the css file, and not the entire computed styles.

Anurag