-1

Say I have a css declaration

.example {
  height: 60px;
}

Is there a way to use Javascript to modify that 60px?

Say for example,

function updateHeight() {
  // add 10px to the css class `example`;
}

So the css class will effectively become

.example {
  height: 70px;
}
davidhu
  • 9,523
  • 6
  • 32
  • 53

1 Answers1

2

You can use code like this:

document.querySelector('.test').style.height = '150px';
.test {
  width : 100px;
  height : 100px;
  background : #0AF;
}
<div class="test"></div>

Of course, you have always the opportunity to make the code as abstract as you desire.

In example you can have a function that can work like that:

// Responsible to set the CSS Height property of the given element
function changeHeight( selector, height ) {
    // Choose the element should get modified
    var $element = document.querySelector( selector );
    // Change the height proprety
    $element.style.height = height;
}

changeHeight( '.test', '150px' );

or you can go even more abstract like that:

// Responsible to modify the given CSS property of the given
// HTML element
function changeCssProperty( selector, property, value ) {
    // Find the given element in the DOM
    var $element = document.querySelector( selector );
    // Set the value to the given property
    $element.style[property] = value;
}

changeCssProperty( '.test', 'width', '200px' );
KodeFor.Me
  • 13,069
  • 27
  • 98
  • 166