Browndog
Browndog

Reputation: 3

Hide <li> using a condition with Jquery

I have html

<ul>
<li>option1: blue </li>
<li>option2: red</li>
<li>option3: </li>
<li>option4: green</li>
<li>option5: </li>
</ul>

What I would like to do is hide the li if after the option: there are no characters/value.

I have limited knowledge using query and I have not yet found an example that would help me find the solution. It would be possible for me to enclose the values red,green etc if necessary.

Is this possible to accomplish with Jquery?

Upvotes: 0

Views: 2389

Answers (3)

Mister Epic
Mister Epic

Reputation: 16723

This one uses regex:

$(function(){
    $('li').each(function(){
        if($(this).text().search(/option\d:\s\s*$/) == 0){
            $(this).hide();   
        }
    });
});

http://jsfiddle.net/pT8s2/

Upvotes: 0

Brian S
Brian S

Reputation: 5056

$('#the-list li').each(function() {
    var text = $(this).text();
    if (!text.match(/option\d+: .+?/g)) {
        $(this).hide();
    }
});

Assuming your list has id="the-list", of course.

Fiddle: http://jsfiddle.net/edJy4/

The regex pattern explained: The text contains a string of characters which begins with "option" followed by one or more digits, a colon, a space, and then one or more characters. If the li does not contain such a string, the li is hidden.

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

Something like this will work:

$("ul li").each(function() {
    var optionText = $(this).text().split(":")[1];
    if (optionText.trim() == "")
        $(this).hide();
});

Fiddle: http://jsfiddle.net/44qeG/

Upvotes: 1

Related Questions