JQuery script is for all my divs in a count script, want it to work individually for each div

I got a jquery script that counts words and adjusts the font size depending on the number of words. The problem is that it counts all attributes with h1 in the parent. I want it to be counted separately for each h1. Initially, the script is marked as h1: first. Here is a script where it considers all h1 in the wofa class:

$(function(){ var $quote = $(".wofa h1"); var $numWords = $quote.text().split(" ").length; if (($numWords >= 1) && ($numWords < 3)) { $quote.css("font-size", "1px"); } else if (($numWords >= 3) && ($numWords < 6)) { $quote.css("font-size", "5px"); } else if (($numWords >= 20) && ($numWords < 30)) { $quote.css("font-size", "10x"); } else if (($numWords >= 30) && ($numWords < 40)) { $quote.css("font-size", "15px"); } else { $quote.css("font-size", "1px"); } 

});

+4
source share
2 answers

I tried the .each () method with your selector and nothing was selected.

I ended up using $ ('. Wofa, h1) .each ():

 $('.wofa, h1').each(function() { var words = $(this).html().split(" "); alert($(this).html() + ' has ' + words.length + ' words'); }); 

Here's the working version of jsfiddle: http://jsfiddle.net/russianator/jKPdQ/

0
source

UPDATED FIDDLE working example

You can use the .each () function

 $('.wofa').each(function() { var quote = $(this).find('h1'); var numWords = quote.text().split(" ").length; console.log(numWords); if ((numWords >= 1) && (numWords < 3)) { quote.css("font-size", "1px"); } else if ((numWords >= 3) && (numWords < 6)) { quote.css("font-size", "5px"); } else if ((numWords >= 20) && (numWords < 30)) { quote.css("font-size", "10x"); } else if ((numWords >= 30) && (numWords < 40)) { quote.css("font-size", "15px"); } else { quote.css("font-size", "1px"); } }); 
+1
source

All Articles