0

I have a grid and in some of the grid items divs the text is too long. I've already added text-overflow:ellipsis, white-space: nowrap, and overflow: hidden. This prevents the text from overflowing as expected. but what I wanted to try, was to detect if there was overflow and if so, decrease the font size.

Below is the JavaScript I was attempting. basically it should loop through all data rows and if overflow is detected change the font size. It doesn't have to be Javascript but I thought this would be my best chance at accomplishing this. however the code is not changing the font size, can anyone please help me with changing the font size? in Javascript, jQuery, CSS, etc.

document.addEventListener('DOMContentLoaded', function() {
   //the div is called data_row adn tehy are dynamically generated
  var text_size = document.getElementsByClassName('data_row');

  for (var i = 0; i < text_size.length; i++) {
    if (text_size.scrollWidth > text_size.clientWidth) {
       //i also tried a specific font size ex. 12px
      text_size.style.fontSize = "small";
    }
  }
});

.data_row {
  text-align: center;
  border: 1 px solid;
  line-height: 25 px;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
isherwood
  • 58,414
  • 16
  • 114
  • 157
SkylarP
  • 39
  • 1
  • 8
  • 1
    Use `forEach` instead, per the linked duplicate. It's much cleaner. The main problem with your code is that you're trying to change `style` as a property of your array. You'd need to select it by index. – isherwood Mar 30 '22 at 16:43

2 Answers2

2

Your variable text_size actually is some kind of an array. You must refer to text_size[i] if you want to access the style etc.

Cheers.

DwightKendall
  • 194
  • 1
  • 3
0

function change(){
  const text = document.getElementById('text');
  text.style.fontSize='36px';
}
<p id="text" style="font-size: 16px">lorem ipsum ...</p>
<button onclick="change()">change</button>
SKONIKS
  • 81
  • 1
  • 4