Search code examples
javascriptchildrencss-selectors

How to check the length of each child in a list and conditionally apply a class to the children of another


I've been searching and searching for the solution to this, but I'm quite new to javascript and I must be missing something obvious.

What I'm trying to do is check each nth-child li by number to see whether they're empty or not, and, if they do contain something, add a class to the corresponding nth-child of another element.

This is what I've ended up at:

if ($('#availList ul li:nth-child(1)').text().length > 0){
$('map area:nth-child(1)').addClass("areaSold");
}

While firebug doesn't have any syntax errors, it doesn't seem to matter if the li is empty or not, because the class will always be applied.

I must be doing something thoroughly dense.

UPDATE:

jsfiddle.net/filmcryptic/ed8LF/1

This actually works as intended... Which means that something is messing up on the site:

Gah.

UPDATE 2:

It works! Thanks blender_noob!


Solution

  • I have created a jsFiddle below. Based on my understanding on your question, you want to add a class to the li if it contains a certain text on it. Please update me if this answers your question. Thanks

    $(function(){
      $('#availList li').each(function(i,val){
         if($(this).text() == "Area Sold"){
           $('#mapArea li:nth-child('+(i+1)+')').addClass('areaSold');
         }else{
           $('#mapArea li:nth-child('+(i+1)+')').addClass('notSold');
         } 
      });
    });
    

    Check sample here: http://jsfiddle.net/tBLhN/