Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a stylesheet using jQuery

How can I change a stylesheet using jquery in div tag on html? or what is the jquery code for changing stylesheets?

in javascript, we use the below code :

<script type="text/javascript">
 function changeStyle() {
 document.getElementById('stylesheet').href = 'design4.css';
 }
</script>

Is there a jQuery way?

like image 788
dimple Avatar asked Dec 23 '22 06:12

dimple


2 Answers

there are better ways to do what you're asking but if you really want to remove and add a remote stylesheet with jquery you can do this:

$('link[href^=old_css_file.css]').attr('href', '/path_to_new_css/file.css');

read more about the ^= attribute selector and the attr() function

like image 167
Jared Avatar answered Jan 07 '23 07:01

Jared


For updating full theme it's best to load a new CSS file. Easiest done on the server side but if you insist on loading dynamically:

// Don't know jQuery, this is regular JS:
var newCss = document.createElement('link');

newCss.rel = 'stylesheet';
newCss.type = 'text/css';
newCss.href = '/path/to/new/cssfile.css';

document.body.appendChild(newCss);
like image 24
slebetman Avatar answered Jan 07 '23 08:01

slebetman