I have an html code which add elements dynamically. On button click i wanted to check whether the elements present inside the div or not
HTML :
<div id="mainDiv">
<span class="child">span1</span>
</div>
<button id="check"></button>
JQuery :
$(function() {
$("#check").click(function(){
// exist or not
});
Try this :
$(function() {
$("#check").click(function(){
if ( $(".child").parents("#mainDiv").length == 1 )
{
// the child element is inside the parent
}
else
{
//it is not inside
}
});
});
hope it is helpfull
You are looking for child element inside parent. It means you know the parent element already exists. So, you should use jQuery context selector as
$(function() {
$("#check").click(function(){
// exist or not
if($('.child', '#mainDiv').length) {
console.log('Yes!! element exists');
} else {
console.log('Nope!!');
}
});
});
You can also use $('#mainDiv').find('.child').length
to check if it contains the element with class child
.
You can find more details on context selectors at http://www.tutorialsteacher.com/jquery/jquery-selectors
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.