Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing CSS properties via JavaScript

I need a function to change the appearance of some elements in my HTML page "on the fly", but I am not able to do it.

The problem is that I cannot use a command like

document.write ('<style type="text/css">body {background-color: #cccccc;}</style>');

because I need to make the changes effective when the page is already loaded, using a link like

<a onmouseclick="Clicker(1)" href="#">clic</a>

and I cannot use a command like

document.body.style.background = '#cccccc';

because I do not know if it can be applied to other not so easy cases, because I need to change the appearance of elements such as td.myclass or sibling elements such as th[scope=col]+th[scope=col]+th[scope=col].

How can I do it? Thanks!

like image 960
tic Avatar asked Mar 14 '10 10:03

tic


People also ask

Can JavaScript change CSS properties?

With JavaScript, we are able to set CSS styles for one or multiple elements in the DOM, modify them, remove them or even change the whole stylesheet for all your page.

Can I change CSS class in JavaScript?

The easiest way of changing a CSS class in JavaScript is by using the className method. Using this method, you can replace any existing classes already present on the HTML element with some other classes. You can specify all the new classes that you want to add as a string with space separation.

Can JavaScript access CSS?

The stylesheet object is available through JavaScript, and allows you to access information about a style sheet referenced from the current web page, such as if it is disabled, its location, and the list of CSS rules it contains.

Can we change CSS properties values using JavaScript or jQuery?

It is possible to change the CSS property of an element by using a simple JavaScript API, but we try to complete this challenge using jQuery css() method.


1 Answers

The stylesheets can be manipulated directly in JS with the document.styleSheets list.

Example:

<html>
<head>
<title>Modifying a stylesheet rule with CSSOM</title>
<style type="text/css">
body {
 background-color: red;
}
</style>
<script type="text/javascript">
var stylesheet = document.styleSheets[1];
stylesheet.cssRules[0].style.backgroundColor="blue";
</script>
<body>
The stylesheet declaration for the body's background color is modified via JavaScript.
</body>
</html>

The example is by Mozilla Contributors and copied from:

  • Using dynamic styling information - Web API Interfaces | MDN
like image 156
kennytm Avatar answered Oct 05 '22 16:10

kennytm