skip to Main Content

I am trying to get the index of a child element in a homegrown photo gallery slider. I seem to get getting an index of 0, but would like to actually get the number of the slide. I’ve tried a lot of things and this is the closest I’ve gotten (tons of tries with just a "-1" as the result). Any tips would be appreciated.

HTML (from an Elixir/Phoenix template)

<div id={"#{@section_id}"} phx-hook="GallerySlider" class="min-w-0">
  <div class="wrapper relative w-full">
    <i id={"left-#{@section_id}"} class="fa-solid fa-angle-left" phx-update="ignore"></i>
    <div class="carousel flex flex-row">
      <%= render_slot(@images) %>
    </div>
    <i id={"right-#{@section_id}"} class="fa-solid fa-angle-right" phx-update="ignore"></i>
  </div>
  <ul id={"dots-#{@section_id}"} class="list-inline dots"></ul>
</div>

JS/TS:

const carousel = this.el?.querySelector<HTMLElement>(".carousel")!;
const carouselChildren = carousel.children;

// Function to get the index of a child element within its parent
function getChildIndex(
  parent: string | any[] | HTMLCollection,
  child: Element,
) {
  for (let i = 0; i < parent.length; i++) {
    if (parent[i] === child) {
      return i;
    }
  }
  return -1; // Child not found
}

// Get the index of a specific child element within the carousel
const targetChild = carouselChildren[0]; // Assuming you want to find the index of the first child element
const index = getChildIndex(carouselChildren, targetChild);

console.log("Index of target child within carousel:", index);

This is the console message:

Index of target child within carousel: 0

2

Answers


  1. As discussed in the comments, the issue was expecting 1-based indexing while using a 0-based language. Changing your code to the following should give the expected output of the current slide number:

    // Function to get the index of a child element within its parent
    function getChildIndex(
      parent: string | any[] | HTMLCollection,
      child: Element,
    ) {
      for (let i = 0; i < parent.length; i++) {
        if (parent[i] === child) {
          // Return the slide number here, not the actual index
          return i + 1;
        }
      }
      return -1; // Child not found
    }
    

    IMO it would make sense to change the function name to something more accurate in this case, i.e. getSlideNumber, but whatever works in your purview.

    Login or Signup to reply.
  2. A simple .querySelectorAll selecting the parent of whatever elements you wish to count provides your array-like object.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search