Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set property 'width' of undefined

function size(){
for(i=0; i<squares; i++){
    document.getElementById('table').innerHTML += "<div class='squareCell' id='objetive"+i+"'></div>";
}
document.getElementsByClassName('squareCell').style.width="300px";
document.getElementsByClassName('squareCell').style.height="300px";}

Still getting "Cannot set property 'width' of undefined" and dont know why. I'm not trying to just solve this, I want to learn what is exactly happening here.

Greetings.

like image 572
RomanVenica Avatar asked Jan 06 '23 11:01

RomanVenica


1 Answers

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a array object

If you have one class name squareCell then you can do it by defining the 0 th index like this

document.getElementsByClassName('squareCell')[0].style.width="300px";
document.getElementsByClassName('squareCell')[0].style.height="300px";

If you want to do with multiple use loop

 var x = document.getElementsByClassName('squareCell');
 for(var i=0; i< x.length;i++){
    x[i].style.width = "300px";
    x[i].style.height = "300px";
 }

OR

var elements = document.getElementsByClassName('squareCell');
  Array.from(elements).forEach(function(element) {
      element.style.height = '50px';
      element.style.width = '50px';
  });

function makeSquare(){
  var elements = document.getElementsByClassName('squareCell');
  Array.from(elements).forEach(function(element) {
      element.style.height = '50px';
      element.style.width = '50px';
  });
}
.squareCell{
    background-color: #ff00ff;
    margin: 5px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
}
<button onclick="makeSquare()">Make Square</button>
<br/>
<div class="squareCell">Test1</div>
<div class="squareCell">Test2</div>
<div class="squareCell">Test3</div>
<div class="squareCell">Test4</div>
<div class="squareCell">Test5</div>
<div class="squareCell">Test6</div>
like image 157
Aman Rawat Avatar answered Jan 08 '23 01:01

Aman Rawat