Search code examples
javascriptjquerylimitdeep-linking

Remove an HTML element depending by it's deep via jQuery


I have nested lists in my HTML page, these lists are managed by a jQuery code which give to the user the interaction of adding rows and children to the list nodes. Every list can contain a div used to add a new list as child. My problem is I would like to add a dynamic limiter to the deep of the elements I can create:

<ul>
    <li>
        <ul>
            <li><div class="add-child"></div></li>
            <li><div class="add-child"></div></li>
            <li><div class="add-row"></div></li>
        </ul>
    </li>
    <li><div class="add-child"></div></li>
    <li><div class="add-child"></div></li>
    <li><div class="add-row"></div></li>
</ul>

The deep could change in the future, I know I can simply use a static selector like this if I want to work with a max of 3 levels of deepness:

$('li li li .add-child').remove();

But I would like a dynamic solution to set the deep via PHP and then limit it via jQuery, how could be my approach to this?


Solution

  • You mean something like this?

    $( '.add-child' ).each( function() {
        if( $( this ).parents( 'li' ).length > someDepthSetByPHP )
        {
            $( this ).remove();
        }
    } );
    

    jsfiddle example