Andrew H
Andrew H

Reputation: 50

jQuery Check parent for class

I'm sure I'm just missing something simple, but I want to change the CSS background-image of all 'li' elements that aren't direct children of a ul with the class of 'library_display'.

HTML:

<ul class="library_display treeview">
    <li>General Competencies
        <ul>
            <li>Achievement Orientation
                <ul>
                    <li class="modal" id="itm_59_modal">
                        <a href="#">Argle Bargle</a>
                   </li>
                </ul>
            </li>
            <li>
                <a href="myUrl" class="modal" id="itm_14_modal">Adaptability</a>
            </li>
        </ul>
    </li>
    <li>Leadership Competencies
        <ul>
            <li>
                <a href="myUrl" class="modal" id="itm_22_modal">Critical Judgment</a>
            </li>
        </ul>
    </li>
    <li>
        <a href="myUrl" class="modal" id="itm_2_modal">Change Management</a>
    </li>
</ul>

JS: This is the code (in a document.ready statement) that is being executed:

if (!$('.treeview li').parents('ul:first').hasClass("library_display")){
    $('.treeview li').css({'background':'url(branch.png) 0px 0px no-repeat'});
}

It's not having any affect right now. If I remove the if statement, it will have the affect I want on all list items, not just the ones I want.

Edit: Thanks for the code block. I was having some issues getting that working properly.

Upvotes: 1

Views: 3843

Answers (3)

jessegavin
jessegavin

Reputation: 75690

This will only affect the <li> elements that are at nested at least two levels within ul.library_display

$(".library_display li li").css({
   'background':'url(branch.png) 0px 0px no-repeat'
});

jQuery Documentation: http://api.jquery.com/descendant-selector/

Upvotes: 3

Blender
Blender

Reputation: 298582

if (!$('.treeview li').parents('ul:first').hasClass("library_display")){
    $('.treeview li').css({'background':'url(branch.png) 0px 0px no-repeat'});
}

This statement is true for some, and false for others, which doesn't make it a valid if statement. You'd want to either iterate over all of the lis, or make a huge selector:

$('.treeview li').each(function()
{
  if ($(this).parents('ul:first').hasClass('library_display')
  {
    $(this).css('background', 'url(branch.png) 0px 0px no-repeat');
  }
});

Upvotes: 0

Mike Thomsen
Mike Thomsen

Reputation: 37524

Try this:

$('ul.library_display').children('li').find('li').css(...);

Upvotes: 0

Related Questions