I have the following HTML on my page;
<div id="c2">
<input type="checkbox" class="expandCollapseSection" id="my_chk">
<span>Header</span>
<div style="" class="contentDiv">
<div class="oj-inputtext oj-form-control oj-component">some things</div>
</div>
</div>
I have the following JS code;
$(".expandCollapseSection").click(function (event) {
if ($(this).prop("checked")) {
$(this).next('.contentDiv').slideDown('slow');
} else {
$(this).next('.contentDiv').slideUp('slow');
}
});
Now my question is $(this).next('.contentDiv')
does not select the contentDiv
I even tried using $(this).closest('.contentDiv')
But still does not select.
Just to add $(".contentDiv")
does get the div though.
Am I doing something wrong here?
use siblings( ".selected" )
$(".expandCollapseSection").click(function (event) {
if ($(this).prop("checked")) {
$(this).siblings('.contentDiv').slideDown('slow');
} else {
$(this).siblings('.contentDiv').slideUp('slow');
}
});
You can try:
$(this).closest('div').find('.contentDiv');
$(".expandCollapseSection").click(function (event) { if ($(this).prop("checked")) { $(this).closest('div').find('.contentDiv').css({'color':'red'}); } else { $(this).closest('div').find('.contentDiv').css({'color':'green'}); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="c2"> <input type="checkbox" class="expandCollapseSection" id="my_chk"> <span>Header</span> <div style="" class="contentDiv"> <div class="oj-inputtext oj-form-control oj-component">some things</div> </div> </div> <div id="c3"> <input type="checkbox" class="expandCollapseSection" id="my_chk"> <span>Header</span> <div style="" class="contentDiv"> <div class="oj-inputtext oj-form-control oj-component">some things</div> </div> </div>
kapantzak's answer is correct.
However you could simply use
$(this).parent().find('.contentDiv');
Slightly more efficient, as you don't have to find closest div.
Try This Code,
$(".expandCollapseSection").click(function (event) {
if ($(this).prop("checked")) {
$(this).closest('#c2').find('.contentDiv').slideDown('slow');
} else {
$(this).closest('#c2').find('.contentDiv').slideUp('slow');
}
});
You may also use nextAll
and shorten your code too, like below.
$(".expandCollapseSection").change(function (event) {
var div = $(this).nextAll('.contentDiv');
var func = this.checked ? 'slideDown' : 'slideUp';
div[func]("slow");
});
Demo@ Fiddle
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.