Reputation: 33
Is it possible to change a css class content with JQuery?
For instance, I have the following page:
html
<div class="foo"> FOO </div>
css
.foo {
color: black;
}
Now I want to change the color in foo
class and maybe add another css attributes in the class. Can I do that with JQuery?
So that I would get
css
.foo {
color: red;
display: inline;
}
I understand that it is possible to modify the style of a specific element in any way I want, but I am interested in changing class content here.
Thank you.
Upvotes: 1
Views: 3850
Reputation: 312
You can use two different css file and switch the URL in link tag on an event.
<link rel="shortcut icon" href="FIRST_CSS_FILE_URL">
$('button').click(function() {
$('link').attr('href', SECOND_CSS_FILE_URL)
})
Upvotes: 0
Reputation: 550
Here is a partial answer to your problem...I think this is what you want:
**JS**
$(document).ready(function() {
let css = "";
$.ajax({
method: 'get',
url: 'test.css',
success: function(response) {
css = response;
let pos = css.indexOf(".foo {");
innerText = " backgound: #ccc";
css = css.substring(0, pos + ".foo {".length) + "\n" + innerText + "\n}";
console.log(css);
}
});
});
**CSS Input**
.foo {
color:black;
}
**CSS Output**
.foo {
backgound: #ccc
}
Assumptions: Your css file is in the same folder, along with the html. The only problem with Javascript is it won't allow you to write to a external file. A check for jQuery plugins turned up with one old plugin called twFile. I could not find its code minified / other. See if you can take this further...just writing to a file (nodejs perhaps).
Upvotes: 0
Reputation: 1780
You can't change the content of external css file. However, you can overwrite it. If the css class is not defined in external css file, you may be able to change it.
I think your purpose is to change the style of all elements that has same class foo
and you want to do it once in one place. In that case, overwriting the style will serve your purpose.
Just make style tag defining the style and insert it to the end of <head></head>
tag
Try this:
$('<style>.foo { color: red, display: inline; }</style>').appendTo('head');
Upvotes: 0
Reputation: 23
Yes you can change whole class using http://api.jquery.com/attr/ as shown below. But you need to assign ID to your element.
<div id="dv_id" class="foo"> FOO </div>
$("#dv_id").attr('class', 'newClass');
You can even addclass or toggleclass like this:
$("#dv_id").addClass('newClass');
$("#dv_id").toggleClass('change_me newClass');
or May be you are looking for Change CSS class properties with jQuery
Hope this will help you solve your question
Upvotes: 0
Reputation: 2516
You can use this
$(".foo").css({"color": "red", "display": "inline"});
Upvotes: 1