简体   繁体   中英

changing style for certain divs with the same className

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM