CarComp
CarComp

Reputation: 2016

How do I apply a stylesheet to an element using Javascript

I need to be able to change out the css applied to the <body> on the fly. How, using javascript, could this be accomplished?

My css is stored as a string in a Javascript variable. I am not working with css files. The css consists of around 50 classes, so it doesn't make sense to apply them one-by-one. I know how this could be accomplished by changing the lowest class, but I'm just trying to see if it's possible to do using Javascript commands and variables.

Pseudo Code

var x = "#nav-bar-wrapper {
  background-color: #4a3e7d;
  padding: 20px 0;
}
#header-nav {
  display: flex;
  justify-content: center;
}...";

function changeCss() {
    var el = $('myelement');
    SomeJavaScriptFunction(el, x);
}

Upvotes: 1

Views: 478

Answers (4)

Brandon Hill
Brandon Hill

Reputation: 1890

As @evolutionbox pointed out, it looks like you want to add new styles to the page. If so, just add them as text content in a style element:

const css = '#nav-bar-wrapper { ... }'
function changeCss() {
    const el = document.createElement('style')
    el.textContent = css
    document.head.appendChild(el)
}

Upvotes: 3

PiggyPlex
PiggyPlex

Reputation: 703

Here's a more JavaScript-y method than using hacky style tags.

const button = document.getElementById('button');
button.onclick = () => {
  [
    [ 'background', 'black' ],
    [ 'color', 'white' ]
  ].map(([ prop, val ]) => {
    button.style[prop] = val;
  });
};
<button id="button">Hello there</button>

You could also try out https://cssinjs.org, which also works great in React.

Perhaps using jQuery's .css() function is worthy too: https://api.jquery.com/css/. It can take an object of CSS properties and apply them to an element.

$('#button').on('click', () => {
  $('#button').css({ background: 'black', color: 'white' });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="button">Hi there</button>

You could also create a new style tag and append it to the body as many people have said. You can even append an external link rel="stylesheet" tag to the header to dynamically add a stylesheet from another URL! An alternative to this would be using the fetch API/jQuery AJAX/xmlhttprequest plus the code below:

$('#button').on('click', () => {
  $('body').append('<style>#button { background: black; color: white; }</style>');
});
<body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <button id="button">Hi there</button>
</body>

Another approach is using classes that you can dynamically add in JavaScript.

$('button').on('click', () => $('#button').addClass('clicked'));
.clicked {
  background: black;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="button">Hi there</button>

Upvotes: 0

Zak
Zak

Reputation: 92

One easy way of doing it would be:

document.querySelector("yourElement").style.cssText += "Your super long string will go here and itll work"

Although, I dont think theres a way of giving different elements a uniqe style all in one line other than appending a style tag to the html. To use the method above, you'd have to separate #nav-bar-wrapper and #header-nav

Just keep in mind to use `` rather than "" to make the string go onto multiple lines

Upvotes: 0

Thierry P. Oliveira
Thierry P. Oliveira

Reputation: 626

You need to get a reference of your html element and after manipulate the DOM, here is an example:

document.getElementById('yourElementIdHere').style.color = 'red';

If you want to get your body reference to manipulate the DOM, you can do it. After this, you can change the style of your body using the style property, and use your string with your css.

document.querySelector("body").style = yourCssStringVar; 

This link can help you, too: JavaScript HTML DOM - Changing CSS

Upvotes: -1

Related Questions