Search code examples
jqueryjquery-traversing

Shorter version for DOM traversing


I have a click event on a .child class. I want to reach the .productHolder div from this class. Now I have a really long selector. I was wondering if there is a shorter version for doing this.

HTML:

<ul class="sm sm-simple">
    <li>
        <a href="#">INTERNET</a>
        <ul>
            <li>
                <a href="#">Prod 1</a>
                <ul>
                    <li><a href="#" class="child">Var M</a></li>
                    <li><a href="#" class="child">Var L</a></li>
                    <li><a href="#" class="child">Var XL</a></li>
                </ul>
            </li>
            <li>
                <a href="#">Prod 2</a>
                <ul>
                    <li><a href="#">Var 1</a></li>
                </ul>
            </li>
        </ul>
        <div class="productHolder"></div>
    </li>
</ul>

JS:

$('.child').on('click', function (event) {
    productHolder = $(event.target).parent().parent().parent().parent().siblings('.productHolder');
});

Solution

  • With your existing HTML structure, you can use .closest() to traverse up to sm-simple then find() can be used.

     productHolder = $(this).closest('.sm-simple').find('.productHolder');