K
K
kunjut192020-05-11 00:43:21
css
kunjut19, 2020-05-11 00:43:21

How to change the style of just one span when iterating over them with getElementsByClassName?

I have a tile of small divs with words inside. Since divs are small, long words won't fit in them. Therefore, I decided to reduce the font a little if the word is too long. But the problem is that when you run through all these tiles and come across one where the word is long, then the font decreases for all tiles (and I only need those in which the text is extra long).
javascript:

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 > 6) {
      tiles[i].querySelector('span').style.fontSize = "0.6rem";
    } 
}

html:
<div class="tile">
    <span>жуткодлинноеслово</span>
</div>
<div class="tile">
    <span>дом</span>
</div>
<div class="tile">
    <span>река</span>
</div>


How to avoid such confusion? And in general, is there a better solution (in terms of code)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2020-05-11
@kunjut19

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question