Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If li has less than 3 characters, hide?

I want to be able to hide list items that have less than 3 characters, how do I do this? What is wrong with my code below?

I am a JavaScript/jQuery newbie.

jQuery().ready(function () {
    if (jQuery('ol li').length < 3) {
        jQuery(this).hide();
    };
});
like image 633
Aaron Brewer Avatar asked Aug 15 '12 21:08

Aaron Brewer


People also ask

What does hide() in jQuery?

jQuery hide() Method The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: To show hidden elements, look at the show() method.


2 Answers

Your code is saying

if (jQuery('ol li').length < 3) {  //If I have less than 3 li elements
    jQuery(this).hide();   //hide the window object
};

What you want to use is filter

$('ol li').filter( function(){ return $(this).text().length<3; } ).hide();

EDIT - Based on your comment in my post: If it is a span tag that could have other data around it:

$('ol li span').filter( function(){ return $(this).text().length<3; } ).parent().hide()

Fiddle running the span example

like image 71
epascarello Avatar answered Sep 30 '22 17:09

epascarello


You'll need to filter out the elements that have a content of less than 3 characters, and hide those :

$(function() {
    $('ol li').filter(function() {
        return $(this).text().length < 3 ;
    }).hide();
});
like image 39
adeneo Avatar answered Sep 30 '22 17:09

adeneo