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).