Get index of child elements with event listener in JavaScript












7















Without changing the HTML, how can I get the index of each slide container when clicked on?



eg. they clicked on 2, how do I get a value such as node[1]?






document.getElementById("slides").addEventListener("click", function(e){
console.log(e.target);
});

<section id="slides">
<div class="slide">1</div>
<div class="slide">2</div>
<div class="slide">3</div>
</section>












share|improve this question





























    7















    Without changing the HTML, how can I get the index of each slide container when clicked on?



    eg. they clicked on 2, how do I get a value such as node[1]?






    document.getElementById("slides").addEventListener("click", function(e){
    console.log(e.target);
    });

    <section id="slides">
    <div class="slide">1</div>
    <div class="slide">2</div>
    <div class="slide">3</div>
    </section>












    share|improve this question



























      7












      7








      7


      2






      Without changing the HTML, how can I get the index of each slide container when clicked on?



      eg. they clicked on 2, how do I get a value such as node[1]?






      document.getElementById("slides").addEventListener("click", function(e){
      console.log(e.target);
      });

      <section id="slides">
      <div class="slide">1</div>
      <div class="slide">2</div>
      <div class="slide">3</div>
      </section>












      share|improve this question
















      Without changing the HTML, how can I get the index of each slide container when clicked on?



      eg. they clicked on 2, how do I get a value such as node[1]?






      document.getElementById("slides").addEventListener("click", function(e){
      console.log(e.target);
      });

      <section id="slides">
      <div class="slide">1</div>
      <div class="slide">2</div>
      <div class="slide">3</div>
      </section>








      document.getElementById("slides").addEventListener("click", function(e){
      console.log(e.target);
      });

      <section id="slides">
      <div class="slide">1</div>
      <div class="slide">2</div>
      <div class="slide">3</div>
      </section>





      document.getElementById("slides").addEventListener("click", function(e){
      console.log(e.target);
      });

      <section id="slides">
      <div class="slide">1</div>
      <div class="slide">2</div>
      <div class="slide">3</div>
      </section>






      javascript






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 17 at 21:51









      Tom O.

      2,64121427




      2,64121427










      asked Feb 17 at 21:41









      totalnoobtotalnoob

      4471934




      4471934
























          2 Answers
          2






          active

          oldest

          votes


















          8














          As long as you're not using arrow function syntax in your callback you can use this to reference the slides element. Using ES6 spread syntax, you can spread its child elements into an array and then use indexOf on that array to get the index of e.target within it:






          document.getElementById("slides").addEventListener("click", function(e) {
          const idx = [...this.children]
          .filter(el => el.className.indexOf('slide') > -1)
          .indexOf(e.target);

          if (idx > -1) {
          console.log(`Slide index: ${idx}`);
          }
          });

          <section id="slides">
          <div class="slide">1</div>
          <div class="slide">2</div>
          <span>Not a slide</span>
          <div class="slide">3</div>
          </section>





          Updated:
          I updated my answer to include only elements having the class slide by implementing the filter method - without this, the index could be thrown off by sibling elements that are not slides.






          share|improve this answer


























          • As a side note, if the sildes contain other elements and not just text, then replace e.target with e.target.closest(".slide") (check closest browser compatibility on MDN)

            – ibrahim mahrir
            Feb 17 at 22:05



















          4














          You can use .indexOf() and .querySelectorAll(), feeding it the list of divs and the target as arguments.






          document.getElementById("slides").addEventListener("click", function(e){
          var nodes = document.querySelectorAll('#slides > .slide');
          console.log(.indexOf.call(nodes, e.target));
          });

          <section id="slides">
          <div class="slide">1</div>
          <div class="slide">2</div>
          <div class="slide">3</div>
          </section>








          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54737958%2fget-index-of-child-elements-with-event-listener-in-javascript%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            8














            As long as you're not using arrow function syntax in your callback you can use this to reference the slides element. Using ES6 spread syntax, you can spread its child elements into an array and then use indexOf on that array to get the index of e.target within it:






            document.getElementById("slides").addEventListener("click", function(e) {
            const idx = [...this.children]
            .filter(el => el.className.indexOf('slide') > -1)
            .indexOf(e.target);

            if (idx > -1) {
            console.log(`Slide index: ${idx}`);
            }
            });

            <section id="slides">
            <div class="slide">1</div>
            <div class="slide">2</div>
            <span>Not a slide</span>
            <div class="slide">3</div>
            </section>





            Updated:
            I updated my answer to include only elements having the class slide by implementing the filter method - without this, the index could be thrown off by sibling elements that are not slides.






            share|improve this answer


























            • As a side note, if the sildes contain other elements and not just text, then replace e.target with e.target.closest(".slide") (check closest browser compatibility on MDN)

              – ibrahim mahrir
              Feb 17 at 22:05
















            8














            As long as you're not using arrow function syntax in your callback you can use this to reference the slides element. Using ES6 spread syntax, you can spread its child elements into an array and then use indexOf on that array to get the index of e.target within it:






            document.getElementById("slides").addEventListener("click", function(e) {
            const idx = [...this.children]
            .filter(el => el.className.indexOf('slide') > -1)
            .indexOf(e.target);

            if (idx > -1) {
            console.log(`Slide index: ${idx}`);
            }
            });

            <section id="slides">
            <div class="slide">1</div>
            <div class="slide">2</div>
            <span>Not a slide</span>
            <div class="slide">3</div>
            </section>





            Updated:
            I updated my answer to include only elements having the class slide by implementing the filter method - without this, the index could be thrown off by sibling elements that are not slides.






            share|improve this answer


























            • As a side note, if the sildes contain other elements and not just text, then replace e.target with e.target.closest(".slide") (check closest browser compatibility on MDN)

              – ibrahim mahrir
              Feb 17 at 22:05














            8












            8








            8







            As long as you're not using arrow function syntax in your callback you can use this to reference the slides element. Using ES6 spread syntax, you can spread its child elements into an array and then use indexOf on that array to get the index of e.target within it:






            document.getElementById("slides").addEventListener("click", function(e) {
            const idx = [...this.children]
            .filter(el => el.className.indexOf('slide') > -1)
            .indexOf(e.target);

            if (idx > -1) {
            console.log(`Slide index: ${idx}`);
            }
            });

            <section id="slides">
            <div class="slide">1</div>
            <div class="slide">2</div>
            <span>Not a slide</span>
            <div class="slide">3</div>
            </section>





            Updated:
            I updated my answer to include only elements having the class slide by implementing the filter method - without this, the index could be thrown off by sibling elements that are not slides.






            share|improve this answer















            As long as you're not using arrow function syntax in your callback you can use this to reference the slides element. Using ES6 spread syntax, you can spread its child elements into an array and then use indexOf on that array to get the index of e.target within it:






            document.getElementById("slides").addEventListener("click", function(e) {
            const idx = [...this.children]
            .filter(el => el.className.indexOf('slide') > -1)
            .indexOf(e.target);

            if (idx > -1) {
            console.log(`Slide index: ${idx}`);
            }
            });

            <section id="slides">
            <div class="slide">1</div>
            <div class="slide">2</div>
            <span>Not a slide</span>
            <div class="slide">3</div>
            </section>





            Updated:
            I updated my answer to include only elements having the class slide by implementing the filter method - without this, the index could be thrown off by sibling elements that are not slides.






            document.getElementById("slides").addEventListener("click", function(e) {
            const idx = [...this.children]
            .filter(el => el.className.indexOf('slide') > -1)
            .indexOf(e.target);

            if (idx > -1) {
            console.log(`Slide index: ${idx}`);
            }
            });

            <section id="slides">
            <div class="slide">1</div>
            <div class="slide">2</div>
            <span>Not a slide</span>
            <div class="slide">3</div>
            </section>





            document.getElementById("slides").addEventListener("click", function(e) {
            const idx = [...this.children]
            .filter(el => el.className.indexOf('slide') > -1)
            .indexOf(e.target);

            if (idx > -1) {
            console.log(`Slide index: ${idx}`);
            }
            });

            <section id="slides">
            <div class="slide">1</div>
            <div class="slide">2</div>
            <span>Not a slide</span>
            <div class="slide">3</div>
            </section>






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Feb 18 at 0:45









            sideshowbarker

            33.4k157997




            33.4k157997










            answered Feb 17 at 21:47









            Tom O.Tom O.

            2,64121427




            2,64121427













            • As a side note, if the sildes contain other elements and not just text, then replace e.target with e.target.closest(".slide") (check closest browser compatibility on MDN)

              – ibrahim mahrir
              Feb 17 at 22:05



















            • As a side note, if the sildes contain other elements and not just text, then replace e.target with e.target.closest(".slide") (check closest browser compatibility on MDN)

              – ibrahim mahrir
              Feb 17 at 22:05

















            As a side note, if the sildes contain other elements and not just text, then replace e.target with e.target.closest(".slide") (check closest browser compatibility on MDN)

            – ibrahim mahrir
            Feb 17 at 22:05





            As a side note, if the sildes contain other elements and not just text, then replace e.target with e.target.closest(".slide") (check closest browser compatibility on MDN)

            – ibrahim mahrir
            Feb 17 at 22:05













            4














            You can use .indexOf() and .querySelectorAll(), feeding it the list of divs and the target as arguments.






            document.getElementById("slides").addEventListener("click", function(e){
            var nodes = document.querySelectorAll('#slides > .slide');
            console.log(.indexOf.call(nodes, e.target));
            });

            <section id="slides">
            <div class="slide">1</div>
            <div class="slide">2</div>
            <div class="slide">3</div>
            </section>








            share|improve this answer




























              4














              You can use .indexOf() and .querySelectorAll(), feeding it the list of divs and the target as arguments.






              document.getElementById("slides").addEventListener("click", function(e){
              var nodes = document.querySelectorAll('#slides > .slide');
              console.log(.indexOf.call(nodes, e.target));
              });

              <section id="slides">
              <div class="slide">1</div>
              <div class="slide">2</div>
              <div class="slide">3</div>
              </section>








              share|improve this answer


























                4












                4








                4







                You can use .indexOf() and .querySelectorAll(), feeding it the list of divs and the target as arguments.






                document.getElementById("slides").addEventListener("click", function(e){
                var nodes = document.querySelectorAll('#slides > .slide');
                console.log(.indexOf.call(nodes, e.target));
                });

                <section id="slides">
                <div class="slide">1</div>
                <div class="slide">2</div>
                <div class="slide">3</div>
                </section>








                share|improve this answer













                You can use .indexOf() and .querySelectorAll(), feeding it the list of divs and the target as arguments.






                document.getElementById("slides").addEventListener("click", function(e){
                var nodes = document.querySelectorAll('#slides > .slide');
                console.log(.indexOf.call(nodes, e.target));
                });

                <section id="slides">
                <div class="slide">1</div>
                <div class="slide">2</div>
                <div class="slide">3</div>
                </section>








                document.getElementById("slides").addEventListener("click", function(e){
                var nodes = document.querySelectorAll('#slides > .slide');
                console.log(.indexOf.call(nodes, e.target));
                });

                <section id="slides">
                <div class="slide">1</div>
                <div class="slide">2</div>
                <div class="slide">3</div>
                </section>





                document.getElementById("slides").addEventListener("click", function(e){
                var nodes = document.querySelectorAll('#slides > .slide');
                console.log(.indexOf.call(nodes, e.target));
                });

                <section id="slides">
                <div class="slide">1</div>
                <div class="slide">2</div>
                <div class="slide">3</div>
                </section>






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Feb 17 at 21:47









                j08691j08691

                167k20197215




                167k20197215






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54737958%2fget-index-of-child-elements-with-event-listener-in-javascript%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Probability when a professor distributes a quiz and homework assignment to a class of n students.

                    Aardman Animations

                    Are they similar matrix