tags:

views:

65

answers:

4

I have a situation where I'm wrapping an image with a span and I want to remove all the CSS from the image and apply it to the span. Is there a way to do this with JQuery?

JQuery:

$(img).wrap('<span />');

Style Sheet:

img { border: 5px solid red; padding: 10px; … needs to allow for anything }

I would like to do this with out editing the HTML or CSS. I need a way to truly remove the CSS from one element and place it on another.

A: 

Can't you just apply your CSS class to the span (and remove from the image)?

See .addClass and .removeClass.

fearofawhackplanet
I'm not using a class to apply the CSS to the image. I could do what your saying but it is not ideal.
Jared Christensen
A: 

I would probably do something like this:

/*CSS*/
.style{border:solid 1px red;}

/*JQuery*/

$("#imageIDHere").removeClass("style");
$("#spanIDHere").addClass("style");

/*or*/

$("#imageIDHere").removeClass("style").parent().addClass("style"); //assuming the span is the parent of the image
Jon
A: 

You can use the removeClass and removeAttr to remove the style depening on your requirement.

Examples:

$('selector').removeClass('some_class'); // this removes some_class
$('selector').removeClass(); // this removes all classes
$('selector').removeAttr('class'); // this removes inline classes
$('selector').removeAttr('style'); // this removes inline styling
$('selector').removeAttr('id'); // this removes id styling
Sarfraz
There's [`.removeAttr()`](http://api.jquery.com/removeAttr/) for this.
Nick Craver
@Nick Craver: Forgot about that (funny) altogether. Thanks man :)
Sarfraz
Will $('selector').removeClass(); remove all styles or only style applied with a class?
Jared Christensen
@Jared Christensen: As the name suggests, it will remove class styling.
Sarfraz
@Jared - It will only remove what's in `style=""` directly on the element though, not from your stylesheet, which seems to be what you're after.
Nick Craver
+1  A: 

There's also toggleClass(), which simply applies the class if it is not already on the element, and removes it if it is.

$("#imageIDHere,#otherThing").toggleClass("theClass");

I have a feeling, looking at your question, that you're planning for some kind of dynamic CSS structure. You can absolutely change classes, CSS selectors and their properties dynamically, using things like this jQuery plugin. However, doing this without any class structure at all or overarching system is most likely setting you up for a lot of headaches down the line.

Trafalmadorian