Note that there are some explanatory texts on larger screens.

plurals
  1. POIf/else conditional based on character count jQuery
    primarykey
    data
    text
    <p>I'm trying to create a jQuery function that counts the character length of each anchor tag &amp; applies a class if the character count is greater than "5". Additionally, if the character count is greater than 7 (4 + 3) then apply a different class.</p> <p>This is where I got to (JSFIDDLE: <a href="http://jsfiddle.net/2mg3q/" rel="nofollow">http://jsfiddle.net/2mg3q/</a>):</p> <p><strong>HTML</strong></p> <pre><code>&lt;div id="global-nav"&gt; &lt;ul id="nav"&gt; &lt;li&gt;&lt;a href="#"&gt;One&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Item5&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Item with11&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;One&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p><strong>CSS</strong></p> <pre><code>#nav{ list-style:none; margin:0; padding:0; } #nav li a{ display:block; padding:5px; border:1px solid #ccc; } #nav li a.TEST1{ border-color:red; } #nav li a.TEST2{ border-color:blue; } </code></pre> <p><strong>JS</strong></p> <pre><code>var navChars = 4; $('#global-nav #nav li a').filter(function() { if($(this).text().length &gt; navChars){ $('#global-nav #nav li a').addClass('TEST1'); }else if($(this).text().length &gt; navChars + 3){ $('#global-nav #nav li a').addClass('TEST2'); } }); </code></pre> <p>Without the "else" statement, both TEST1 &amp; TEST2 classes were being applied to the anchor tags. With the else statement, only TEST1 is applied to the anchor tags.</p> <p>The original JS I was using &amp; that I have based the above on worked great for a singular condition but now I need to accommodate for at least 2 possible character lengths. </p> <p>Original JS that I have altered (hacked):</p> <pre><code>var navChars = 13; $('#global-nav #nav li a').filter(function() { return $(this).text().length &gt; navChars; }).addClass('navMultiLine'); </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload