Disgeae
Disgeae

Reputation: 80

jQuery: if ID is equal to statement

I'm working on a code that does a action if one of the LI's is selected. So if one of the first LI's is 'current' I want to perform an action on it, the code:

<div id="types">
    <div id="division1">
        <ul id="selection1">
            <li id="current"><a href="#" name="1-1"></a> </li>
            <li><a href="#" name="1-2"></a></li>
            <li><a href="#" name="1-3"></a></li>
        </ul>
    </div>
    <div id="division2">
        <ul id="selection2">
            <li><a href="#" name="2-1"></a></li>
            <li><a href="#" name="2-2"></a></li>
            <li><a href="#" name="2-3"></a></li>
        </ul>
    </div>
</div>

jQuery:

if (jQuery("#types div ul:nth-child(1)").attr("ID") == "current") {
    *do this*
}

Anyone has any idea what I'm doing wrong?

Upvotes: 0

Views: 5053

Answers (2)

Henrik Andersson
Henrik Andersson

Reputation: 47172

I'll throw my two cents in here

if($('#types div ul > li:first').is('#current')){
    *do this*
}

I threw out 1 pseudoselector, 1 extra function call and 1 comparison for the built in is() which I find to be a bit more readable.

And made a Fiddle for demo

update

What you had faulty was that you had set display:none on the parent div #Uitleg1, #Uitleg2 and when you tried to .show() on your child it inherited the display:none.

I updated the CSS with a new selector.

#Uitleg1, #Uitleg2 div {
    display: none;
}

and removed display: none; from the one above that. Your code now works as expected.

Made another Fiddle for demo

Upvotes: 0

Adil Shaikh
Adil Shaikh

Reputation: 44740

ul do not have id current but li does

try this -

if (jQuery("#types div ul:nth-child(1) li:first").attr("ID") == "current") {
    *do this*
}

Upvotes: 4

Related Questions