Get index of child elements with event listener in JavaScript
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>javascript
add a comment |
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>javascript
add a comment |
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>javascript
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
javascript
edited 3 hours ago
Tom O.
2,52321326
2,52321326
asked 3 hours ago
totalnoobtotalnoob
3951833
3951833
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
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.
As a side note, if the sildes contain other elements and not just text, then replacee.targetwithe.target.closest(".slide")(checkclosestbrowser compatibility on MDN)
– ibrahim mahrir
2 hours ago
add a comment |
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>add a comment |
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 :)
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
As a side note, if the sildes contain other elements and not just text, then replacee.targetwithe.target.closest(".slide")(checkclosestbrowser compatibility on MDN)
– ibrahim mahrir
2 hours ago
add a comment |
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.
As a side note, if the sildes contain other elements and not just text, then replacee.targetwithe.target.closest(".slide")(checkclosestbrowser compatibility on MDN)
– ibrahim mahrir
2 hours ago
add a comment |
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.
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>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 replacee.targetwithe.target.closest(".slide")(checkclosestbrowser compatibility on MDN)
– ibrahim mahrir
2 hours ago
add a comment |
As a side note, if the sildes contain other elements and not just text, then replacee.targetwithe.target.closest(".slide")(checkclosestbrowser 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
add a comment |
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>add a comment |
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>add a comment |
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>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>answered 3 hours ago
j08691j08691
167k20193213
167k20193213
add a comment |
add a comment |
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 :)
add a comment |
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 :)
add a comment |
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 :)
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 :)
answered 48 mins ago
ZER0ZER0
17.5k33543
17.5k33543
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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