Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, I could do this 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 <div>s.

like image 934
J-bob Avatar asked Feb 28 '14 18:02

J-bob


1 Answers

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).

like image 120
Zhihao Avatar answered Sep 22 '22 15:09

Zhihao