1

Hello and thank you for reviewing my question, i'm having trouble setting the height on a div element using javascript because element.style.height is not working for me.

The code below does not work and will only have alert("test1") activate, thus meaning that the element.style.height does not work

function PHSetter() {
        alert("test1");
        document.getElementsByClassName("MainContent").style.height = "100px";
        alert("test2");
    }

The code below also does not work and will have both alert("test1") and alert("test2") activated, i think meaning that the document.getelementbyclassname command was indeed working, but when it was time to set the height it simply had an error.

 function PHSetter() {
            alert("test1");
            var x = document.getElementsByClassName("MainContent");
            alert("test2");
            x.style.height = "100px";
            alert("test3");
        }

The code below is the css code for the div with the class name of MainContent.

.MainContent {
    border-style: solid;
    border-width: 1px;
    position : relative;    
    width    : 1150px;
    height   : 100%;
    left     : 50%;
    top      : 625px;
    z-index: 1;
    margin-left : -575px;
    margin-top  : -625px;
}

any help?

DiscreteTomatoes
  • 769
  • 1
  • 14
  • 30

1 Answers1

1

getElementsByClassName returns array-like nodelist...

Either you iterate through all the elements if there are many elements having class as MainContent or if there is only one element having the class as MainContent then Use document.getElementsByClassName("MainContent")[0]

Try this:

function PHSetter() {
  document.getElementsByClassName("MainContent")[0].style.height = "100px";
}
.MainContent {
  border-style: solid;
  border-width: 1px;
  position: relative;
  width: 1150px;
  height: 100%;
  left: 50%;
  top: 625px;
  z-index: 1;
  margin-left: -575px;
  margin-top: -625px;
}
<button onclick='PHSetter()'>Go</button>
<div class='MainContent'>Content</div>
Rayon
  • 36,219
  • 4
  • 49
  • 76