Kyle Coots
Kyle Coots

Reputation: 2131

JQuery Selecting specific li element

Ok I have been struggling with this for a little bit. I'm still learning JQuery.

Here is what I have:

The Script:

$('ul li.error').animate({
    height: 'toggle',
    opacity: 'toggle'
    }, {
    duration: 500,
    specialEasing: {
    width: 'linear',
    height: 'easeInOutCubic'
    },
    complete: function() {

    $(this).each(function(){

        $(this).delay(4000);

        $(this).animate({
            height: 'toggle',
            opacity: 'toggle'
        }, {
            duration: 7000,
            specialEasing: {
            width: 'linear',
            height: 'easeInOutCubic'
        },
        complete: function(){
            $(this).delay(1000);
                $(this).parent().next().find('li input').css('border-color', 'red');
                $('#somediv').slideDown();  
            }

        });

    });

    }
});

The Html:

<div>
   <ul>
 <li class="error">(Error Message if any)</li>
 <li class="label"><label></li>
 <li class="input"><input></li>

 <li class="error">(Error Message if any)</li>
 <li class="label"><label></li>
 <li class="input"><input></li>
   </ul>
</div>

What I'm trying to do is select the li element that has the input and change the border color. But I only want to change the border color of the one where there was an error message.

How can I do this? Any help would be appreciated, Thanks!

Upvotes: 1

Views: 2285

Answers (1)

iConnor
iConnor

Reputation: 20189

Here is a example I have just made, it's not good to be selecting elements like this though.

$('.error').each(function(){
    var next = $(this).next();
    for( var i = 0; i < 5; i++ ) {
        if( next.hasClass('input') === false ) {
            next = next.next();
        } else {
            next.css('border', '1px solid red');
            break;
        }
    }
});

Demo: http://jsfiddle.net/2rdrr/

It loops through the next elements to .error and tries to find .input if it hasn't found it within 5 tries, it will give up. If it finds the element it adds the border and breaks the loop so it doesn't keep looking.

Note: This is not very clever, you are in control of your page so you should know where the elements are instead of having to look for them.

A better way of doing this is.

<div>
   <ul>
      <li class="error">(Error Message if any)</li>
      <li class="label"><label></li>
      <li class="input"><input></li>
   </ul>
   <ul>
      <li class="error">(Error Message if any)</li>
      <li class="label"><label></li>
      <li class="input"><input></li>
   </ul>
</div>

Then you can just do this.

$('.error').parent().find('.input').css('border', 'red');

Upvotes: 1

Related Questions