changing style for certain divs with the same className

Viewed 44

I have many small divs with the same classname. Every div has a span with text. But since those divs are pretty small long words doesn't fit in them. I want to make font size smaller for those divs that have long words. But my code changes font

var tiles = document.getElementsByClassName('tile');
  for (var i=0; i<tiles.length; i++) {
    var textLength = tiles[i].textContent.length;
    var fontSize = window.getComputedStyle(tiles[i].querySelector('span')).fontSize;

    if(textLength > 9) {
      tiles[i].querySelector('span').style.fontSize = "0.6rem";
    } 
}
<div class="tile">
    <span>itsaveryverylongword</span>
</div>
<div class="tile">
    <span>bird</span>
</div>
<div class="tile">
    <span>keyboard</span>
</div>

size for all divs. How to fix that?

1 Answers

to get span text length

var textLength = tiles[i].querySelector('span').textContent.length;

var textLength = tiles[i].textContent.length; this is length of full <span>bird</span> with span tag too.

var tiles = document.getElementsByClassName('tile');
  for (var i=0; i<tiles.length; i++) {
    var textLength = tiles[i].querySelector('span').textContent.length;
    console.log(tiles[i].textContent.length);
    var fontSize = window.getComputedStyle(tiles[i].querySelector('span')).fontSize;

    if(textLength > 9) {
    console.log(tiles[i].textContent.length);
      tiles[i].querySelector('span').style.fontSize = "0.6rem";
    } 
}
<div class="tile">
    <span>itsaveryverylongword</span>
</div>
<div class="tile">
    <span>bird</span>
</div>
<div class="tile">
    <span>keyboard</span>
</div>

Related