Larsss
Larsss

Reputation: 57

Jquery iterate through class, count sting length, if shorter than X do something

I have a site with x instances of a class (they are loaded dynamically through php). In each instance of the class there is a different amount of characters and i want all instances of the class with less than 110 characters to be narrower than the rest.

I have made it this far, which work with one instance of the class , but when two classes are loaded it calculates the total length of all instances of the class. I have looked into .each() for Jquery, but i cant seem to get the syntax right.

JQuery

if ($(".quotecontent").text().length < 110) {
        $(".quote").css("width", 500);
        //alert($(".quotecontent").text().length);
    }

HTML

<div class="quote">
<div class="quotestart"></div>
<div class="quotecontent"><p>We have a new toy!</p>
<div class="author">- Fernando Alonso</div></div>
<div class="quoteend"></div>
</div>

<div class="quote">
<div class="quotestart"></div>
<div class="quotecontent"><p>Fight to fly, fly to fight, fight to win.</p>
<div class="author">- Motto of the U.S. Navy Fighter Weapons School, TOPGUN</div></div>
<div class="quoteend"></div>
</div>

Upvotes: 1

Views: 2563

Answers (2)

adeneo
adeneo

Reputation: 318182

$(".quotecontent").filter(function() {
    return $(this).text().length < 110;
}).parent('.quote').css("width", 500);

​​​​​​​​​​​​​​​​ FIDDLE

Upvotes: 2

Tats_innit
Tats_innit

Reputation: 34107

Demo http://jsfiddle.net/B3Uwj/11/

Please let me know if I missed anything.

Hope this helps.

code

$(".quotecontent").each(function() {

    if ($(this).text().length < 110) {
        $(this).parent(".quote").css("width", 500);
        //alert($(".quotecontent").text().length);
    }
});​

Upvotes: 4

Related Questions