Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

javascript - JQuery add class to parent element

I have to set a class name on a (li) element. This script find all the (a) elements in the list, and creates a click event.

jQuery("#" + ElementID).find(TagName).click(function () {

    GetPageByUrl(jQuery(this).attr("href"));
    jQuery(this).parent().addClass('yourClass');
    //ChangeSelectedMenuItem(this);
    return false;
});

The parent of every (a) element is a (li) element

But nothing happens when this line is executing jQuery(this).parent().addClass('yourClass');

Everything else is working just fine.

What am I doing wrong here?


Okay, but it still won't work. It won't add any class jQuery(this).addClass('yourClass'); Should add a class to the (a) element, but it doesn't?

question from:https://stackoverflow.com/questions/3482543/jquery-add-class-to-parent-element

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Specify the optional selector to target what you want:

jQuery(this).parent('li').addClass('yourClass');

Or:

jQuery(this).parents('li').addClass('yourClass');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...