jquery: if (target) is child of ('.wrapper') then (do something)
var target开发者_运维百科 = $(this).attr("href");
if {target is child of ('.wrapper')} then (do something)
simple syntax? can someone show me the correct syntax here?
if($(target).parents('.wrapper').length > 0) {
//do something...
}
.has()
is maybe the mose convenient syntax:
if( $('.wrapper').has($(target)) ) {
// do something
}
Even more 'powerful' (in terms of performance) is $.contains()
. So an ideal algorithm should look like:
var $wrapper = $('.wrapper'),
$target = $(this).attr('href');
if( $.contains($wrapper[0], $target[0]) ) {
// do something
}
Reference: .has(), $.contains()
Here's a tidier way: bind it as a jQuery plugin. You might find it be easier to understand and use.
$.fn.isChildOf = function(element)
{
return $(element).has(this).length > 0;
}
Usage:
if ( $('.target').isChildOf('.wrapper') ) {
//do all the things.
}
Small change to Jacob's code, if the child is deeper than one level in.
if($(target).parents('.wrapper').length) {
//do something...
}
you can use parent or parents method like in the links
http://jsfiddle.net/6BX9n/
http://jsfiddle.net/6BX9n/1/
I know this is old post, but it could be useful for someone. It seems to me that in many cases using .closest() would have better performance:
if ($(target).closest('.wrapper').length){
// your code here
}
<div class="parent">
<div class="child">
</div>
</div>
$(".child").is(".parent .child")
You can use jQuery's .find()
method for this like below:
if ( $( '.wrapper' ).find( $( e.target ) ).length > 0 ) {
// target is a child of $( '.wrapper' )
}
$( document ).on('click', function ( e ) {
if ( $( '.wrapper' ).find( $( e.target ) ).length > 0 ) {
// do staff here, target's inside $( '.wrapper' )
alert( 'target is a child of .wrapper' );
} else {
alert( 'target is not a child of .wrapper' );
}
} );
.wrapper {
width: 200px;
height: 200px;
background: black;
display: flex;
}
.wrapper:before {
content: '.wrapper';
color: #FFF;
position: absolute;
}
.child {
width: 80px;
height: 80px;
background: red;
margin: auto;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="child">.child</div>
</div>
Can't you bind another event?
$('.wrapper *').click(function() {
// will execute on childrens of .wrapper
});
You can use jQuery's is function,
var target = $(this).attr("href");
if ($('a[href="'+target+'"]').is(('.wrapper > *') {
//do soemthing
}
'.wrapper > *'
is a css selection for the explicit first level children of .wrapper
. If you need any nested anchor element then use '.wrapper *'
instead
精彩评论