Reacting
Reacting

Reputation: 6123

How can I use a data-attr within a href instead of an id?

Lets say I have this html in the body element:

<a href="#fragment-1">Go to href</a>

And I need that anchor to take me to this other element within the same page:

<div id="fragment-1">Some content</div>

There I am doing it with an id, but I would like to use a data-attribute.

Like this anchor: <a href="data-attr">Go to href</a>

taking to this div: <div data-attr="fragment-1">Some content</div>

How can I achieve that?

Upvotes: 0

Views: 723

Answers (1)

BoltClock
BoltClock

Reputation: 723729

You can't. Since data attributes

  • are user-defined, and
  • don't have uniqueness semantics built into them,

they can't act like IDs for the purposes of anchors.

You could use JavaScript to scroll the page to whichever element matches document.querySelector('[data-attr="your-fragment"]'), but that's JavaScript territory. You won't get this behavior for free in HTML itself.

Upvotes: 5

Related Questions