开发者

jquery access nested div

Here is my question. I am having this simple menu.

<div id="menu"> 
    <ul>
        <li> <a id="home" href="home.html"> home </a>           </li>
        <li> <a id="profile" href="profile.html"> profile</a>   </li>       
    <ul>
</div>

and I wanna to use jQuery to add a class ".active" to the a tag with the id="home".

What I am writing is: $('a#home').addClass("activ开发者_运维知识库e"); but is not working. How can I access this nested tag and add some class??

Any suggestions would be highly appreciated! Thanx


The typical mistake is to put your jQuery code in the header, but not wrapped in a ready event.

Make sure you have:

$(document).ready(function(){
 $('a#home').addClass('active');
});

see here for a live test: http://jsfiddle.net/QdVLs/ (remember jsfiddle automartically wraps any code in a ready method like above)


You may need to put use it after document ready

$(document).ready(function(){
    $('a#home').addClass("active");
});

The reason can be when your javascript is executed the dom may not have created the element a#home/#home. This case can be handled using the ready method as shown above.

You can test the case by just adding a alert($('a#home').length) statement before your code. It should alert 1 else you can try to use the ready() and try again, this time put the alert() inside the ready() method.


$('a#home').addClass("active"); should work.

Do you have other element with the same id ?

Where did you put this code ? (It should be executed after document ready event)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜