Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local id-s for HTML elements

I am developing a kind of HTML+JS control which can be embedded into various web pages. I know nothing about those pages (well, I could, but I don't want to). The control consists of one root element (e.g. DIV) which contains a subtree of child elements. In my script, I need to access the child elements. The question is: how can I mark those child elements to distinguish them?

The straightforward solution is using id-s. The problem here is that the id must be unique in the scope of the entire document, and I know nothing about the document my control will be embedded into. So I can't guarantee the uniqueness of my id-s. If the id-s are not unique, it will work (if used with care), but this does not conform with the standard, so I can meet problems with some new versions of the browsers, for example.

Another solution is to use the "name" attribute. It's not required to be unique -- that's good. But again, the standard allows the presence of "name" attribute only for a restricted set of element types. For example, the "name" attribute is invalid for DIV elements.

I could use, for example, the "class" attribute. It seems to be OK with the standards, but it's not OK with the meaning. "class" should be used for other purposes, and this may be confusing.

Can anybody suggest some other options to implement local id-s for HTLM elements?

like image 892
C-F Avatar asked Nov 22 '12 20:11

C-F


1 Answers

You could use the HTML5 data-* attributes so you can give them a custom name with the right meaning:

https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes

Do something like:

<div id="element-id" data-local-id="id-value">
  ...
</div>

and get the value in JavaScript with:

const el = document.getElementById('element-id');
const { localId } = el.dataset;
like image 70
tbraun89 Avatar answered Oct 11 '22 20:10

tbraun89