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();
};
});
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.
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
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With