Amar
Amar

Reputation: 11

Changing css property dyamically using javascript

.gridArea {
  margin-left: 12px;
  margin-bottom: 12px;
  height: 200px;
  width: 98%;
  overflow: auto;
  border: solid 1px #333366;
}

If I have the above css class defined in a file xyz.css and I want to change dynamically the property from "overflow" to "hidden" using JavaScript, how can it be done ?

Upvotes: 0

Views: 83

Answers (3)

Tibos
Tibos

Reputation: 27823

The simplest solution to change the property for both current and future elements is to override the overflow property's value in a dynamically created stylesheet element:

var s = document.createElement('style');
s.innerHTML = '.gridArea {overflow: hidden;}';
document.querySelector('head').appendChild(s);

DEMO: http://jsbin.com/galicuto/1/edit

If you only need to change the value for a single element, you could change it via the style property:

var el = document.querySelector('.gridArea');
el.style.overflow = 'hidden';

If you want to change it for all the elements currently in the document, you can do the same, but iterate over the results given by document.querySelectorAll.

Upvotes: 0

Denis Tsoi
Denis Tsoi

Reputation: 10404

Using Query Selector

var el = document.querySelector('.gridArea');
el.style.overflow = "hidden";

Upvotes: 0

Banana
Banana

Reputation: 7463

you can apparently alter the css, some guy explains it Here

or you can change the elements instead of touching the css

var elements = document.getElementsByClassName('gridArea');

for (var i = 0; i < elements.length; i++) {
    elements[i].style["overflow"]="hidden";
}​

or if you are willing to try jQUery(which is simply a free javascript extension, you can do it in one line:

$(".gridArea").css({"overflow":"hidden"});

Upvotes: 1

Related Questions