DEV Community

Cassidy Williams
Cassidy Williams

Posted on • Originally published at blog.cassidoo.co

3

HTML "self-awareness" with sibling indexing in JavaScript

This is a super specific use case, but if you have an HTML element and you want it to be more "self-aware", you can do:

let element = document.getElementById('whatever');

// To get an array of siblings
[...element.parentElement.children]

// To get current index of self
[...element.parentElement.children].indexOf(element)
Enter fullscreen mode Exit fullscreen mode

What we're doing here is:

  • Getting our HTML element
  • Getting the parent of our HTML element
  • Getting the children of the parent
  • Spreading it into an array (because it's an HTMLCollection otherwise, you can also use Array.from)
  • Getting the index of our element amongst all of its siblings

I figured this out after working on a framework-less project, where I wanted an HTML <button> to be able to tell the function it called its own index.

Example HTML:

<div>
    <button onclick="whoami(event)">Some button</button>
    <button onclick="whoami(event)">Some other button</button>
    <button onclick="whoami(event)">And other button</button>
</div>
Enter fullscreen mode Exit fullscreen mode

And the corresponding example JavaScript:

function whoami(event) {
    let element = event.currentTarget;
    let currentButtonIndex = [...element.parentElement.children].indexOf(element);
    // ...and so on
}
Enter fullscreen mode Exit fullscreen mode

Anyway, I thought this was cool, hope it's useful for you!

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay