Skip to content Skip to sidebar Skip to footer

Uncaught Typeerror: Cannot Read Property 'style' Of Null At Htmlbuttonelement.

The following code, meant for a collapsible text is throwing out the following error: Uncaught TypeError: Cannot read property 'style' of null at HTMLButtonElement. the line where

Solution 1:

The button is the only child of the p element. So there is no nextElementSibling. You could either remove the p element or set levcontent to this.parentElement.nextElementSibling.

Furthermore I found a little typo: You used content.scrollHeight instead of levcontent.scrollHeight in the else block.

Here is the modified and working code:

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
  coll[i].addEventListener("click", function() {
    this.classList.toggle("lev-active");
    var levcontent = this.parentElement.nextElementSibling;
    if (levcontent.style.maxHeight){
      levcontent.style.maxHeight = null;
    } else {
      levcontent.style.maxHeight = levcontent.scrollHeight + "px";
    } 
  });
}
.collapsible {
    height: 40px;
    background-color: #444;
    color: white;
    cursor: pointer;
    padding: 0px10px0px10px;
    margin: 2%4%2%4%;
    width: 93%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 14px;
    text-transform: capitalize;
}

.lev-active, .collapsible:hover {
    background-color: #555;
}

.collapsible:after {
    content: '\002B';
    color: white;
    font-weight: bold;
    float: right;
    margin-left: 5px;
}

.lev-active:after {
    content: "\2212";
}

.levcontent {
     padding: 018px;
     max-height: 0;
     overflow: hidden;
     transition: max-height 0.2s ease-out;
     background-color: #f1f1f1;
}
<p><buttonclass="collapsible">Levering</button></p><divclass="levcontent"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p></div>

Post a Comment for "Uncaught Typeerror: Cannot Read Property 'style' Of Null At Htmlbuttonelement."