EddyR
EddyR

Reputation: 6941

jquery hidden parent

ummm, probably a simple one... the code below only works with visible (show()) elements how do I get it select the first hidden element instead?

Jquery

$(".postSelectedRules").each(function() {
    $(this).parents("#idruleB-"+$(this).attr("id").substr(8)+":hidden:first").css('background', '#bbbbbb');
});

Html

<a id="idruleA-1" class="postSelectedRules" href="#">1</a>
<div class="postStuff">
    <div class="postRules">
        <span id="idruleB-1" class="postRulesSelect">1</span>
        <span id="idruleB-2" class="postRulesSelect">2</span>
    </div>
</div>

Upvotes: 2

Views: 2835

Answers (3)

KyleFarris
KyleFarris

Reputation: 17538

Just FYI... You should NEVER have repeated IDs. You will find that your code will run much faster if you make sure of this. It would make much more sense to use a Class in this situation.

Let's assume that you XHTML is like this:

<div class="someClass" style="display:block;" id="someElement_1">
    <div class="postSelectedRules"></div>
</div>
<div class="someClass" style="display:none;" id="someElement_2">
    <div class="postSelectedRules"></div>
</div>
<div class="someClass" style="display:none;" id="someElement_3">
    <div class="postSelectedRules"></div>
</div>

You would do this to select '#someElement_3" (the first hidden element):

$('.someClass:hidden:first').css({backgroundColor:'#bbb'});

I believe that's basically what you are trying to do.

Upvotes: 0

cletus
cletus

Reputation: 625037

Your code doesn't make a lot of sense. You're searching the parents of the matching nodes for node that has the same ID as the current node? IDs should be unique.

As for excluding hidden items the general form would be something like:

$(this).parents(":someClass:visible:first").addClass("blah");

Also instead of:

css('background', '#bbbbbb');

I'd highly recommend using classes instead if possible. Adding and removing CSS attributes is problematic. Classes are easy.

Upvotes: 4

AutomatedTester
AutomatedTester

Reputation: 22418

You can do it with

$(".postSelectedRules:hidden").each(function() {
    $(this).parents("#"+$(this).attr("id")).css('background', '#bbbbbb');
});

The :hidden in the selector looks for items that are hidden.

I hope that helps.

Upvotes: 0

Related Questions