简体   繁体   中英

find element of particular class that happens before element with known ID, in jQuery

I have the following piece of HTML. Using jQuery it is easy to find the element with given ID ("ctl00_JQueryContent_PhenoTree_i1_ItemLabel" in the example). My task then to alter the SPAN right before it that has class "rtUnchecked". I further need to remove rtUnchecked and replace it with other CSS class.

<span class="rtSp"></span><span class="rtPlus"></span>
<span class="rtUnchecked"></span><div class="rtIn">
            <div class="rtTemplate">
                <table> <tbody><tr><td>
 <span id="ctl00_JQueryContent_PhenoTree_i1_ItemLabel">
 (...)

I obviously can not use class sejector, because there are other SPANs of class rtUnchecked on the page. How I'd write a selector for JQuery that helps me to find this element?

Have you tried?

//select element
var $elem = $('#ctl00_JQueryContent_PhenoTree_i1_ItemLabel')
            .prev('span.rtUnchecked')
            .last();
//switch class
$elem.removeClass('rtUnchecked').addClass('otherClass');

Try this:

 $('#ctl00_JQueryContent_PhenoTree_i1_ItemLabel')
 .parents().find('.rtUnchecked').last().css({'color':'red', 'border': '1px solid red'});

demo here: http://jsfiddle.net/wCBhT/

you can test it also:

$('#ctl00_JQueryContent_PhenoTree_i1_ItemLabel')
 .parents().find('.rtUnchecked').removeClass('rtUnchecked').addClass('new-classname');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM