DEV Community

Cover image for How to fix the value of dynamically generated html id attribute
Mamun Abdullah
Mamun Abdullah

Posted on

2

How to fix the value of dynamically generated html id attribute

The main issue:

If you set a value to an id attribute started with a number, CSS won't work with that and the navigation to that id will fail to execute.

A short description:

If you need to set the value of id (s) from a unique data source, if the source-data contains such a value started with a number, if you need to set target to that id in your project, your code won't work with that part, and it will be very difficult to find out the problem if the project is a big one.

Sometimes, you can not imagine the reason behind this issue because the other parts with the same code will be working!

So, it is very common to get trouble while generating it automatically from a data source.

How to solve this issue:

To solve this issue we can add a text before the source data, like:

id={`mytext${source-data}`}
Enter fullscreen mode Exit fullscreen mode

and set the target value like this:

{`#mytext${source-data}`}
Enter fullscreen mode Exit fullscreen mode

This is just an example (JavaScript, React.js), you need to follow your own code relevant syntax to implement the solution.

Follow me on:
LinkedIn
GitHub
Twitter

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

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