Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing object ID in HTML document: id vs data-id vs?

I would like to have an opinion on storing RESTful object IDs in document for accessing it later from JavaScript.

Theoretically speaking using id for addressing elements in HTML doesn't cut it anymore. Same element can be repeated twice on the page say in "Recent" and "Most Popular" queries which breaks the main point of using id.

HAML even has this nice syntax sugar:

%div[object]

becomes:

<div class="object" id="object_1">

But like I said, seems that it is not a good approach. So I am wondering what is the best way to store objects id in DOM?

Is this the current proper approach?

<div data-id="object_1">
like image 555
firedev Avatar asked Sep 03 '25 03:09

firedev


2 Answers

An ID is intended to uniquely identify an element, so if you have a case where you want to identify two or more elements by some common identifier, you can use ID but it may not be the best option in your case.

You can use IDs like:

<div id="d0">Original Div</div>
<div id="d0-0">Copy of original div</div>
<div id="d1">Another original Div</div>
<div id="d1-0">Another copy of original div</div>
<div id="d1-1">Another copy of original div</div>

and get all the d1 elements using:

document.querySelectorAll('[id^=d1]');

or just d1 divs:

document.querySelectorAll('div[id^=d1]')

You could also use a class:

<div id="d0" class="d0">Original Div</div>
<div id="..." class="d0">Copy of original div</div>
<div id="d1" class="d1">Another original Div</div>
<div id="..." class="d1">Another copy of original div</div>
<div id="..." class="d1">Another copy of original div</div>

and:

document.querySelectorAll('.d1')

Or use data- attributes the same way. Whatever suits.

You can also have a kind of MVC architecture where an object stores element relationships through references based on ID or whatever. Just think outside the box a bit.

like image 140
RobG Avatar answered Sep 05 '25 17:09

RobG


The purpose why data-selectors where introduces is because the users neednt want to use class or anyother attributes to store value.Kindly use data-selectors itself. In order to make it easy to access them use attributes selector i.e. [attribute='value']. PFB the fiddle for the same and also the example

jsfiddle

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-git2.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body onload="call()">
  <div id="1" data-check='1'></div>
  <div id="2" data-check='1'>sdf</div>
  <div data-check='1'>sdf</div>
  <div data-check='1'>sdf</div>
  <div data-check='1'>sdf</div>
</body>
</html>

function call()
{

$("#1").html($('[data-check="1"]').length);

  $("#2").html( document.querySelectorAll('[data-check="1"]').length);

}

Output: 5 5 sdf sdf sdf

like image 21
wallop Avatar answered Sep 05 '25 17:09

wallop