J-bob J-bob - 3 months ago 7
jQuery Question

Can the HTML data attribute hold a reference to a DOM element?

Is it possible with the HTML

data-
attributes to hold a reference to another DOM element. For example, could do with jquery:

var domel1 = document.getElementByID("#mydiv")
var domel2 = document.getElementByID("#mydiv2")
$(domEl1).attr('data-domel', domel2)


Then later on, with jquery I would do:

var domel1 = document.getElementByID("#mydiv")
var domel2 = $(domel2).data('domel')
$(domel2).html("blahblahblah"


This might seem like a trivial example because I could just reference domel2 with the same
id
like I did at first, but there are cases where this could be useful for representing relationships between divs.

Answer

Yes and no. You cannot store a reference to a DOM element in a data- attribute. However, you can associated a reference to a DOM element to another element using jQuery .data(), which are already using:

$someElement.data('name', someOtherElement);

From the jQuery documentation:

The .data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore from memory leaks.

Note that using .data() to set data will add it to the data store but not add it as a data- attribute in the DOM. However, using .data() to read data will check the data store as well as the data- attribute (if one exists and there's no data store value with the given key).

Comments