Home > Software engineering >  How do I pass between children by jQuery?
How do I pass between children by jQuery?

Time:02-22

$('[data-target="#exampleModal"]').on("click", function () {
    var element = $(this).parent();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div >
        <div  id="">
            <button data-toggle="modal" data-target="#exampleModal">
                <img src="./img/watch-page.png" alt=""  />
            </button>
        </div>

        <div >
            <button data-toggle="modal" data-target="#exampleModal">
                <img src="./img/watch-page.png" alt=""  />
            </button>
        </div>

        <div >
            <button data-toggle="modal" data-target="#exampleModal">
                <img src="./img/search-page.png" alt=""  />
            </button>
        </div>
   </div>

How can I find out the order of the element for all of the children?

And how can I move to the next child or the one before it?

CodePudding user response:

First, you were not selecting the elements properly. When you call

$('[data-target="#exampleModal"]')

It return array of elements so you should loop over them and then add events for click.

You can see below, index is the order of the button and button is the element so you can walk from there to reach parent etc.

$.each($('[data-target="#exampleModal"]'), function(index, button){
    $(button).on("click", function () {
        var element = $(this).parent();
        console.log(element);
    });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div >
        <div  id="">
            <button data-toggle="modal" data-target="#exampleModal">
                <img src="./img/watch-page.png" alt=""  />
            </button>
        </div>

        <div >
            <button data-toggle="modal" data-target="#exampleModal">
                <img src="./img/watch-page.png" alt=""  />
            </button>
        </div>

        <div >
            <button data-toggle="modal" data-target="#exampleModal">
                <img src="./img/search-page.png" alt=""  />
            </button>
        </div>
   </div>

  • Related