jquery: if (target) is child of ('.wrapper') then (do something)

Viewed 38425
var target = $(this).attr("href");

if {target is child of ('.wrapper')} then (do something)

simple syntax? can someone show me the correct syntax here?

10 Answers

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>

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

Related