-3

I want to set an element's height to window.innerheight but I have to do it in CSS because somehow I don't have access to that element to use javascript to change it's style. Is there a way to do that? like changing a CSS class in javascript?

I tried this:

document.getElementById('root').style.setProperty('--view-height', window.innerHeight +'px');

and in CSS:

.menu {
    height: var(--view-height) !important;
}

and it works but CSS Variables is not supported in older browsers so I can't use that, but I want something similar.

EDIT: There is many answer yet they all use javascript, i said i CAN NOT USE js to set the element style! i want to do it only by css class style

rojadesign
  • 385
  • 3
  • 14
mahboub_mo
  • 2,908
  • 6
  • 32
  • 72

5 Answers5

0

Set height in javascript instead use variables

document.getElementById('root').style.height=window.innerHeight +'px';

See example:

 document.getElementById('root').style.height=window.innerHeight +'px';
#root{
background-color:red;
}
<div id="root"></div>

To your edit no use js use height:100vh; :

#root{
height:100vh;
background-color:red;
}
<div id="root"></div>
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
0

In modern browsers you can use:

document.getElementById("MyElement").classList.add('MyClass');
document.getElementById("MyElement").classList.remove('MyOtherClass');

Although, for accomplishing your specific case, I'd go with לבני מלכה's answer.

0

Maybe use proper CSS instead:

window.innerHeight +'px' results in the same height as using 100vh. The unit vh means "viewport height" and 100vh is the full height of the inner window.

See: https://developer.mozilla.org/en-US/docs/Web/CSS/length#Viewport-percentage_lengths

feeela
  • 29,399
  • 7
  • 59
  • 71
0

using vh unit is the proper way to do this.. (although Mahboobeh Mohammadi said that it isn't compatible with ios) height: 100vh; is the full height of the view..

Me1o
  • 1,629
  • 1
  • 6
  • 8
-1

For Normal Js

function addClassById (_id,_class) {
  document.getElementById(_id).classList.add(_class);
}

function removeClassById (_id,_class) {
  document.getElementById(_id).classList.remove(_class);
}

addClassById("root","newClass")

I advise to you use JQUERY it s very easy to use. Put this cdn link on your head tag then use it.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

//This is for change css
$("#root").css({
"background-color": "yellow", 
"font-size": "200%"
});



 // This is how to add class
$("#root").addClass('newClass');





// This is how to remove class
 $("#root").removeClass('newClass')

I hope it help you.

Ramazan Zülkarneyn
  • 153
  • 1
  • 4
  • 14