DEV Community

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

Posted on

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

Top comments (0)