DOM Elements are identified by their "id" value when it is present. But in absence of it can we write a function that generates an "id" ? If called multiple times the function need to return the same ID for the same DOMElement.
Asked
Active
Viewed 218 times
1 Answers
2
Every element has its css selector that points to it uniquely, you can add id for example by jquery:
$(*unique selector*).attr('id', 'element_id');
and afterwards to reference this element by this id.
You can also call this element by its css selector everytime - if it's unique enough, it can act like an id, but it introduces additional overhead.
For example, your question's selector is:
var el = $('#question table td.postcell div.post-text p');
You can set it's id:
el.attr('id','your_question');
Now you can reference it by this new id:
alert($('#your_question').text());
try it in your Firebug console.

n-dru
- 9,285
- 2
- 29
- 42
-
I am looking for this *unique selector* that you mentioned. How do you construct such a selector given the reference of a node ? – Diptendu Mar 13 '15 at 07:05
-
This probably needs a whole lot of additional `:nth-child`s to tie it down in most cases. – Ulrich Schwarz Mar 13 '15 at 07:32
-
@UlrichSchwarz Sure, but that's what ids are for, not to have to traverse DOM this way controlling potential changes in DOM structure. – n-dru Mar 13 '15 at 07:34
-
@n-dru: I'm not disagreeing, I'm just remarking that `#question table td.postcell div.post-text p` is a special case of only one `p` child. – Ulrich Schwarz Mar 13 '15 at 07:36
-
@n-dru: You don't always have the option of adding an ID, e.g. if you're consuming markup from a third-party resource. This is where having a unique selector can be useful. – BoltClock Mar 13 '15 at 07:39
-
@BoltClock Yes, but in that case the overhead from referencing by css selector vs by id plays much les role. – n-dru Mar 13 '15 at 07:43
-
1@Diptendu: That's a separate question altogether - see http://stackoverflow.com/questions/4588119/get-elements-css-selector-without-element-id – BoltClock Mar 13 '15 at 07:48
-
@n-dru: I think performance is only going to be a real issue if the OP needs to call the selector as often as a browser needs to evaluate it in CSS - in which case, they really should be calling it just once and caching the reference for future use (and that is assuming the location of the element will never change during the lifetime of the DOM). – BoltClock Mar 13 '15 at 07:50