ALAN
ALAN

Reputation: 495

Check if li exists within ul

I have one ul called : id = listProjectRelated

On the if condition in document ready, I need to add the li element whose id will be: liProfessionalMemberships

I want to add the li item if it does not exist in the ul element. How can I do that?

 if ($('#hdnValueProMembershipSoid').val() != "0") {
     btnAddMore.show();
     $('#listProjectRelated').empty();
     $('#listProjectRelated').append("<li id='liProfessionalMemberships'>Professional Membership</li>");
 }

I have almost 6 different li elements that I need to add.

Upvotes: 2

Views: 10570

Answers (6)

Matt Zeunert
Matt Zeunert

Reputation: 16561

Check if $("#liProfessionalMemberships").length is 0. If it is add the li to the page.

If you have several list items you can put them in a list with their respective ids and titles (the visible text):

var lis = [
     {id: "liProfessionalMemberships", title: "Professional Membership"},
     {id: "...", title: "..."}
];

for (var i=0;i<lis.length;i++)
{
    var li = lis[i];
    if ($("#" + li.id).length === 0)
    {
        $('#listProjectRelated').append("<li id='" + li.id + "'>" + li.title + "</li>");
    }
}

Upvotes: 1

Learner
Learner

Reputation: 4636

You can do like the following:

if($("#listProjectRelated #liProfessionalMemberships").length) {
       $("#listProjectRelated ul").append('<li id="liProfessionalMemberships">Professional Membership</li>');
}

Upvotes: 0

Mr. tk
Mr. tk

Reputation: 179

$('#listProjectRelated li').length should do the trick.

Upvotes: 4

Bhushan Firake
Bhushan Firake

Reputation: 9448

 if($('#liProfessionalMemberships').length == 0)
    {
        $('#listProjectRelated').append("<li id='liProfessionalMemberships'>Professional Membership</li>");
    }

Upvotes: 0

BenM
BenM

Reputation: 53198

You need the length property of the object:

if($('#hdnValueProMembershipSoid').val() != "0") 
{
    btnAddMore.show();
    $('#listProjectRelated').empty();

    if($('#liProfessionalMemberships').length == 0)
    {
        $('#listProjectRelated').append("<li id='liProfessionalMemberships'>Professional Membership</li>");
    }
}

Upvotes: 0

Popnoodles
Popnoodles

Reputation: 28409

You do mean if the element by the id "liProfessionalMemberships" doesn't exist then add it don't you?

if (!$('#liProfessionalMemberships').length) {
    // ok to add stuff
}

Upvotes: 1

Related Questions