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 17 hours ago









      Tom O.

      2,55821326




      2,55821326










      asked 18 hours ago









      totalnoobtotalnoob

      4001833




      4001833
























          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
            17 hours ago



















          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
              17 hours ago
















            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
              17 hours ago














            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 15 hours ago









            sideshowbarker

            32.4k147595




            32.4k147595










            answered 18 hours ago









            Tom O.Tom O.

            2,55821326




            2,55821326













            • 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
              17 hours ago



















            • 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
              17 hours ago

















            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
            17 hours ago





            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
            17 hours ago













            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 18 hours ago









                j08691j08691

                167k20193213




                167k20193213






























                    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

                    How to label and detect the document text images

                    Vallis Paradisi

                    Tabula Rosettana