Get index of child elements with event listener in JavaScript












6















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





























    6















    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



























      6












      6








      6


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









      Tom O.

      2,52321326




      2,52321326










      asked 3 hours ago









      totalnoobtotalnoob

      3951833




      3951833
























          3 Answers
          3






          active

          oldest

          votes


















          7














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



















          3














          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































            0














            First of all, I would use closest (or a polyfill) to ensure the reference to the actual slide from the element clicked; then I would use the spread syntax to transform the NodeList in an array, and be able to use the method findIndex.



            The code would be something like that:



            document.getElementById("slides").addEventListener("click", ({target}) => {
            // get the reference to the slide;
            // since `target` might be a child element of the actual slide.
            // E.g. `<div class="slide"><b>1</b></div>`
            // If you click on the text "1", `target` would be `<b>`.
            const slide = target.closest(".slide");

            // if we clicked inside a "slide" element
            if (slide) {
            // get all the children's of the parent of the slide clicked,
            // and find the index inside this array where the array's item is
            // equals to the element clicked
            const index = [...slide.parentNode.children].findIndex(child => child === slide);
            console.log(index)
            }
            });


            It's actually more concise when you remove all the comments :)






            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

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              7














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
















              7














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














              7












              7








              7







              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 11 mins ago









              sideshowbarker

              32.4k147595




              32.4k147595










              answered 3 hours ago









              Tom O.Tom O.

              2,52321326




              2,52321326













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













              3














              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




























                3














                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


























                  3












                  3








                  3







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









                  j08691j08691

                  167k20193213




                  167k20193213























                      0














                      First of all, I would use closest (or a polyfill) to ensure the reference to the actual slide from the element clicked; then I would use the spread syntax to transform the NodeList in an array, and be able to use the method findIndex.



                      The code would be something like that:



                      document.getElementById("slides").addEventListener("click", ({target}) => {
                      // get the reference to the slide;
                      // since `target` might be a child element of the actual slide.
                      // E.g. `<div class="slide"><b>1</b></div>`
                      // If you click on the text "1", `target` would be `<b>`.
                      const slide = target.closest(".slide");

                      // if we clicked inside a "slide" element
                      if (slide) {
                      // get all the children's of the parent of the slide clicked,
                      // and find the index inside this array where the array's item is
                      // equals to the element clicked
                      const index = [...slide.parentNode.children].findIndex(child => child === slide);
                      console.log(index)
                      }
                      });


                      It's actually more concise when you remove all the comments :)






                      share|improve this answer




























                        0














                        First of all, I would use closest (or a polyfill) to ensure the reference to the actual slide from the element clicked; then I would use the spread syntax to transform the NodeList in an array, and be able to use the method findIndex.



                        The code would be something like that:



                        document.getElementById("slides").addEventListener("click", ({target}) => {
                        // get the reference to the slide;
                        // since `target` might be a child element of the actual slide.
                        // E.g. `<div class="slide"><b>1</b></div>`
                        // If you click on the text "1", `target` would be `<b>`.
                        const slide = target.closest(".slide");

                        // if we clicked inside a "slide" element
                        if (slide) {
                        // get all the children's of the parent of the slide clicked,
                        // and find the index inside this array where the array's item is
                        // equals to the element clicked
                        const index = [...slide.parentNode.children].findIndex(child => child === slide);
                        console.log(index)
                        }
                        });


                        It's actually more concise when you remove all the comments :)






                        share|improve this answer


























                          0












                          0








                          0







                          First of all, I would use closest (or a polyfill) to ensure the reference to the actual slide from the element clicked; then I would use the spread syntax to transform the NodeList in an array, and be able to use the method findIndex.



                          The code would be something like that:



                          document.getElementById("slides").addEventListener("click", ({target}) => {
                          // get the reference to the slide;
                          // since `target` might be a child element of the actual slide.
                          // E.g. `<div class="slide"><b>1</b></div>`
                          // If you click on the text "1", `target` would be `<b>`.
                          const slide = target.closest(".slide");

                          // if we clicked inside a "slide" element
                          if (slide) {
                          // get all the children's of the parent of the slide clicked,
                          // and find the index inside this array where the array's item is
                          // equals to the element clicked
                          const index = [...slide.parentNode.children].findIndex(child => child === slide);
                          console.log(index)
                          }
                          });


                          It's actually more concise when you remove all the comments :)






                          share|improve this answer













                          First of all, I would use closest (or a polyfill) to ensure the reference to the actual slide from the element clicked; then I would use the spread syntax to transform the NodeList in an array, and be able to use the method findIndex.



                          The code would be something like that:



                          document.getElementById("slides").addEventListener("click", ({target}) => {
                          // get the reference to the slide;
                          // since `target` might be a child element of the actual slide.
                          // E.g. `<div class="slide"><b>1</b></div>`
                          // If you click on the text "1", `target` would be `<b>`.
                          const slide = target.closest(".slide");

                          // if we clicked inside a "slide" element
                          if (slide) {
                          // get all the children's of the parent of the slide clicked,
                          // and find the index inside this array where the array's item is
                          // equals to the element clicked
                          const index = [...slide.parentNode.children].findIndex(child => child === slide);
                          console.log(index)
                          }
                          });


                          It's actually more concise when you remove all the comments :)







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 48 mins ago









                          ZER0ZER0

                          17.5k33543




                          17.5k33543






























                              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

                              Alcázar de San Juan

                              Griza ansero

                              Heinkel He 51