Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using jQuery, how can I remove a dynamically added class to the head of a page

I use an inline editor to edit css classes, when a change is made I wish to remove the class definition and add it again, also user has option to delete the element using it so I need to delete the definition.

Adding works using this code:

$("<style>").prop("type", "text/css").html( "#my_element_"+MaxElements+" {"+ xCSSCode +"}").appendTo("head");

however I can't seem to remove this class which is inserted into the head of the page as follows:

<style type="text/css">#my_element_1 {border-radius: 12.5px;
...
}</style>
like image 265
Ekim Avatar asked Jul 23 '13 22:07

Ekim


People also ask

How do I delete a dynamic class?

Adding and removing class dynamically to an element can make a web page more interactive. Using jQuery it becomes a simple and easy task to add and remove class dynamically. It just needs to call a jQuery function with the selector where we want to add a class or remove a class.

How do I remove a class from a DOM element?

To remove a class from an element, you use the remove() method of the classList property of the element.

How add or remove a class in jQuery?

jQuery Manipulating CSSaddClass() - Adds one or more classes to the selected elements. removeClass() - Removes one or more classes from the selected elements. toggleClass() - Toggles between adding/removing classes from the selected elements. css() - Sets or returns the style attribute.


2 Answers

create a style tag:

var style = $("<style />", {
                id  : 'myStyleTag',
                type: 'text/css',
                html: "#my_element_"+MaxElements+" {"+ xCSSCode +"}"
}).appendTo("head");

to remove

style.remove();
// or
$('#myStyleTag').remove();
like image 151
adeneo Avatar answered Oct 12 '22 22:10

adeneo


I would store the elements in an object:

var styles = {};

...

styles[some_identifier] = $("<style>", {
    type: "text/css",
    html: "#my_element_"+MaxElements+" {"+ xCSSCode +"}"
}).appendTo("head");

You can remove the style tag easily:

styles[some_identifier].remove();
like image 35
Blender Avatar answered Oct 12 '22 22:10

Blender