简体   繁体   中英

jquery selector of parents

I have this html structure:

<div class="dropdownedit">
<div class="dropbtn">textxyz</div>
<div class="dropdown-content" style="display: none;">
<div href="#" class="ocond" id="text1">text1</div>
<div href="#" class="ocond" id="text2">text2</div>
<div href="#" class="ocond" id="text3">text3</div>
<div href="#" class="ocond" id="text4">text4</div>
</div></div>

in jquery I call a on-click-event for the class "ocond":

now I want to modify the text in class dropbtn (there are around 100 with this name). So i tried it with this jquery line:

  $(this).parents('.dropbtn').text("conditionvalue");

I also tried:

$(this).parents('.dropdownedit').siblings('.dropbtn').text("conditionvalue");

but I had no success. anyone can point me to the right selector? thanks in advance!

Use $(this).parent() to navigate from the .ocond to the .dropdown-content , and then you can use .siblings('.dropbtn') to get to the .dropbtn sibling:

 $('.ocond').on('click', function() { $(this).parent().siblings('.dropbtn').text("conditionvalue"); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="dropdownedit"> <div class="dropbtn">textxyz</div> <div class="dropdown-content"> <div href="#" class="ocond" id="text1">text1</div> <div href="#" class="ocond" id="text2">text2</div> <div href="#" class="ocond" id="text3">text3</div> <div href="#" class="ocond" id="text4">text4</div> </div> </div> 

Your

$(this).parents('.dropbtn')

didn't work because .dropbtn is not a parent of the .ocond s, and

$(this).parents('.dropdownedit').siblings('.dropbtn')

didn't work because the .dropbtn is not a sibling of the .dropdownedit .

You should probably only use .parents if you want to select multiple parents of the element in question - otherwise, probably better to use .closest (which will select one ancestor matching the passed selector) or .parent (which will select just the immediate parent element).

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