Unique identifier for HTML elements - javascript

Besides the ID, if you say you want a unique identifier for an HTML element (let’s say a div).
I browsed the DOM for something (like a number or string) that was unique for each element; but the DOM was big and I failed to find that on the Internet.
Is there a property (in the DOM obviously) that is unique only to that element? (Other than the ID and also you don't specify it, but it comes when the DOM is constructed.)

Depending on the objective, here are two suggestions.
Unless you actually need to express the id as some kind of string, you can save the normal DOM reference.
If you do need to express it as a string for some reason, then you'll need to assign a unique id yourself.
var getId = (function () {
var incrementingId = 0;
return function(element) {
if (!element.id) {
element.id = "id_" + incrementingId++;
// Possibly add a check if this ID really is unique
}
return element.id;
};
}());

The only other identifier I can think of is the XPath of the element in the document.
For instance, the title link inside the heading of this very page has an XPath of
/html/body/div[3]/div[2]/div/h1/a
But like Pekka already said, it depends on what you want to do. And I don’t think you can get the XPath easily from the DOM in JavaScript, despite XPath being available nowadays in JavaScript engines.

Internet Explorer has a property, "uniqueID", for every element. The problem is that the other browsers don't support it.

You can use a library or roll your own to create a unique identifier. jQuery has .data():
Store arbitrary data associated with the matched elements or return
the value at the named data store for the first element in the set of
matched elements.

I just encountered the same situation, and while I was looking into some DOM elements in the Chrome developer tools inspector, I noticed that they all seem to have a property like jQuery11230892710877873282 assigned with a unique number.
Obviously the number after 'jQuery' is different every time you load the page. My guess is that jQuery is generating this internally every time it tries to access or manipulate any DOM element.
I played a little bit with it, and it looks like elements that are never accessed/manipulated by jQuery may not have this property, but the moment you do something like $(elem), the property will be there. So, since we're using both jQuery and Lodash, I devised the following function to return a unique ID regardless of whether the element actually has a DOM id attribute.
_.reduce(
$(elem),
function(result, value, key) {
if(_.startsWith(key, 'jQuery'))
return value;
},
0)

There is the name attribute that can be addressed by document.getElementByName.
I don't think other unique identifiers exist - even though you could simulate one by setting a property (like title) to a unique value, and then query for that. But that is kludgy.

Related

Associate an element with a unique number

I'm looking for a way to associate a DOM element with a unique number, such that no other element in the DOM will be associated with that number. Obviously, I can't use an Id attribute because not all elements have an Id.
The most obvious way to do this is to (somehow) acquire a number that will give the element's position within the DOM, but I'm not sure if this is feasible. Ultimately, given an arbitrary element from the DOM, I'd like to have a way of mapping that element to a number.
Everyone is asking why I need to do this -- given a DOM element, I need to use that element as a key in a JS Object. JS Objects must be strings. So, technically, I do not need a unique number, per se, but I need a unique value that can be turned into a "short string" and used as the key in a JS object.
Technically, I do not need a unique number, per se, but I need a unique value that can be turned into a "short string" and used as the key in a JS object.
I see that you have jQuery tagged. This might be a possible solution to your problem. jQuery has a way to associate an element to an object:
var ele = /* your element */
$(ele).data({name: "Paul"});
// later you can use the element as a key
$(ele).data(); //returns {name: "Paul"}
This will avoid the whole "assigning unique id" mess and just let jQuery does all the hard work for you (creating a map data structure).
Edit by Roamer-1888
Basically, I need to "tag" an element uniquely so that if I encounter the same element in the future, I will know I've seen it before. The "tag" value will be the key in my JS object. I will associate various values in the tagged element. I don't want to use Map or WeakMap because they might not be supported on all browsers.
To meet this requirement, you would typically use jQuery's .data() as follows :
//...
var elementData = $(ele).data('myApplication');
if(!elementData) { // this element was not previously encountered
elementData = {
prop_A: ...,
prop_B: ...,
prop_C: ...
};
$(ele).data('myApplication', elementData);
}
// Here `elementData` is guaranteed to exist and its properties can be read/written.
//...
This technique is particularly useful for preseving state in jQuery plugins. Here is an example
Multiple applications/modules can do this without interfering with each other.
I'm guessing that there might be a better way to solve your problem if we understood what the real problem was. But, at any point in time, you can find what position an element is at (if it is currently inserted in the document) with something like this:
var items = document.getElementsByTagName("*");
If you needed to then get a unique index for a DOM element (at this particular point in time), you can do so by just searching for it in that HTMLCollection. It's position in the collection is guaranteed to be a unique index.
But, of course as the DOM is modified, this HTMLCollection will change as will the index.
If you wanted to assign a non-changing unique index, you could just assign a property to each DOM element based on a monotomically increasing counter.
var idCntr = 1;
function assignIds() {
var items = document.getElementsByTagName("*");
for (var i = 0; i < items.length; i++) {
if (!items[i]._uniqueId) {
items[i]._uniqueId = idCntr++;
}
}
}
You can call this function as many times as you want and it will assign new unique IDs to any DOM elements that don't yet have an id, but will leave ids that were already assigned the same (so they will never change).
If you just want to be able to generate a unique ID for any given DOM node such that you can always have the same ID for that DOM node, then you can just again use a monotomically increasing counter.
var idCntr = 1;
function assignId(elem) {
if (!elem._uniqueId) {
elem._uniqueId = idCntr++;
}
return elem._uniqueId;
}
You can then call this on any DOM element that you want to assign a unique ID to and it will both assign the id to the element and return the id that it assigned. If you pass it an element that already has an id, it will leave that id in place and just return it.
Based on your latest edit, it appears you're just trying to generate an id string that you can use as a key in a JS object. You can certainly use the above assignId() function for that.
In a modern browser, you can also use a Map or a
WeakMap object which will accept the DOM object itself as the key - you don't need to manufacture your own string key. You can then look it up directly with the DOM element too (since it's the key).

Why no error when accessing a DOM element that doesn't exist?

I have some divs with partial views in them. Why would a reference to a div that doesn't exist not show some kind of error? For example, I only have one taskN div right now:
<div id="task1">
#Html.Partial("~/Views/PartialViews/TaskDosCommand.cshtml")
</div>
This is my jQuery to show the div:
$('#task' + task.PrestoTaskType).show();
When task.PrestoTaskType is 1, the task1 div correctly displays. However, when task.PrestoTaskType is anything but 1, like 2, then nothing displays (which is good), but there is no error; no error shows on the web page, and nothing displays in the Chrome developer tools console:
Shouldn't some kind of error display when accessing a DOM element that doesn't exist?
No, because what jQuery does is .show() all elements that the jQuery object wraps. If that's no elements at all, then so be it.
That's precisely a monad-like aspect of jQuery that makes it so useful: imagine the code you 'd have to write if things didn't work that way:
var $whatever = $(...);
if ($whatever.length) $.doSomething();
This is simply worse: you need to introduce a variable (in order to avoid waste) and a conditional... for what gain exactly?
If you want to see what jQuery matched you can do that very easily with .length as above, perhaps also using .filter in the process.
One of the nice things about jQuery is that all jQuery elements return a collection, whether that is 0, 1, or many elements. This is convenient because you don't need to check the size of the collection or wrap it in an array yourself when you want to call methods on it (each for example doesn't break for 0-1 elements).
While what you're talking about is frustrating in this particular case, it is better for jQuery to work this way so you don't have to do those sorts of checks everywhere else.
If you want to branch code based on the existence of such an element, you can do this:
var task = $('#task' + task.PrestoTaskType);
if (task[0]) {
task.show();
} else {
// task not found
// take appropriate steps
}
The [0] accessor will return the first DOM element in the jQuery object or undefined if the jQuery object is empty. Since your jQuery object was constructed with an ID selector, it either contains exactly one DOM element or it's empty.

Strange ie behaviour with jquery inArray

Hello this seems to be working on IE8 :
var clsName = link.parents("div.fixed_column").attr("class").split(" ");
if($.inArray("column_one", clsName)
While this one reports error (Object expected errror in jquery).
var clsName = link.parents("div.fixed_column").attr("class");
What is the right way to do this? I thought purpose of inArray was that jquery will handle cross browser issues.
Unfortunately, this is indirectly answering your question, but... You seem to be looking to detect if an element has a class, and since you're already using jQuery, just use the hasClass method - http://api.jquery.com/hasClass/
For your specific code, try:
if (link.parents("div.fixed_column").hasClass("column_one")) {
// It has the "column_one" class
}
The more immediate answer to your question is that link.parents("div.fixed_column").attr("class") returns a single string. When the jQuery selector (div.fixed_column) returns multiple elements, which is very possible when using classes, using jQuery methods that get information (like .attr, using one parameter...to "get" the value) return the first matched element's value only.
So say the selector matches 3 elements:
["<div id='div30' class='fixed_column div30_class'></div>",
"<div id='div2' class='fixed_column div2_class'></div>",
"<div id='div17' class='fixed_column div17_class'></div>"]
Then the value returned from .attr("class") will be: fixed_column div30_class because it's the first matched element.
I'm not sure, but I think you're expecting jQuery to return an array of all the matched elements' values, which it just doesn't. So that doesn't mean jQuery isn't handling cross-browser issues, it just means you need to look up what the method does/returns.
I could've sworn that jQuery 2.0 has options for doing what you want - directly from calling the getters (or something similar), but I can't find it anymore :( Maybe I'm remembering incorrectly. Anyways, you could easily use $.each and/or $.map to look at every matched element, but it depends on what you were really trying to do with it.
You can't read the attributes of multiple elements into an array with .attr("class"). But why don't you just target the desired class in the selector like this?
var cols = link.parents("div.fixed_column.column_one");
Then change your conditional to check for an empty set:
if(cols.length) { ...

can I use document.prototype.getElementById to get an element in another element, not in the whole document

I recently found on this javascript tip :
element_number = Array.prototype.indexOf.call(element_1, element_2);
It allows developers to use the indexOf method on an object wich is not an Array.
I would like to know if it is possible to use a similar syntax to call the getElementById method but not on the whole document (document.getElementById), just on an element like this :
my_div_2 = document.prototype.getElementById.call(div_1, "id_of_my_div_2");
The idea is that my document contains tabs and elements having the same id can be present several times in the document.
If it is not possible, did somebody write a function doing that :
Search in an element another element by id.
No, but you can accomplish what you want using querySelector instead.
my_div_2 = div_1.querySelector("#id_of_my_div_2");
Not supported in IE6/7.
Docs: MDN element.querySelector()
That said, duplicate IDs are invalid.
This technique is useful if the same script is used on different pages where the ID may or may not be in a particular container.
No. The getElementById method must be applied on objects of type Document, otherwise it would throw a WRONG_THIS_VALUE exception. You could try it with
myDiv1 = document.getElementById("div1");
myDiv2 = document.getElementById.call(myDiv1, "div2"); // no ".prototype"!
This makes no sense as only one element with a given id is possible in a document.
So the only right syntax would be
my_div_2 = document.getElementById("id_of_my_div_2");
Don't reuse an id in a document. You probably can achieve the desired result using classes instead of id.

Javascript - extract object ID from a Javascript object

So I am not sure if my title is clear enough. I essentially have a div saved as a Javascript object which looks like this: [div#field_30.checkbox_group]
The field_30 is the ID which I am trying to extract here. doing something like object.id is not working. Does anyone know how to get the ID?
Note: I saved the object like this: var object = $(".workspace .selected"); which grabs the currently selected div inside the object called workspace. Sorry is this is a rookie mistake, I just can't seem to find anything anywhere. Thanks for the help...
var object = $(".workspace .selected"); will return a jQuery wrapped element that has jQuery properties and methods rather than element properties and methods. This means that any of
object[0].id
object.prop("id")
object.attr("id")
should work, but the 1st option should be the best performance-wise. It gets the id property of the the 1st element contained by the jQuery object, which is your div.
Your object is in fact a jQuery object, not a dom object.
To use the dom object use,
object[0].id
Or using, jquery, (Since it is already there)
object.prop('id');
You can use either $jquery_object.attr('id') or $jquery_object.eq(0).id
See this for exemple: http://jsfiddle.net/cquuT/
In this case it looks like object is the result of a jQuery select. To get to the actual DOM object you need to use [0]. Then you can access the id property
object[0].id
I don't see a complete answer here, so I'll provide my own.
If you're using jQuery selector $(), then you'll get jQuery-wrapped collection, not a single element.
(I assume now that you're using jQuery 1.5.2, the same as StackOverflow uses now.)
Universal solution to get ids of all elements returned by selector is:
.map(function(){ return this.id; })
Running $(".post-text").map(function(){ return this.id; }) on current page will return something like: ["", "", "", "", ""]
To get id of the first element returned by selector use:
.attr('id')
Running $("div").attr('id') on current page will return "notify-container".
Since jQuery 1.6 you can also use .prop('id') here.
If you know, that query will return only one element or you just want the first element matching given selector, then use .attr which is obviously a simpler solution.

Categories