1

I'd like to push data to the data attribute of an element using jQuery. is that even possible?

the element looks like this:

<span id="el" data-id="[1]"></span>

and I'd like to get

<span id="el" data-id="[1, 2]"></span>

how can achieve that? I know I can set the data value with $('#el').data('id', [1, 2, 3, 4]); but as I get the ids from a PHP file (therefore I don't know the ids I'll get) so I guess I have to use something similar to push().

Mad
  • 21
  • 2

2 Answers2

0

You can use JSON.parse() and then add data and convert it back to string to set it as data attribute

const el = document.getElementById('el');

const pushElementToData = (elm, prop, data) => {
  const prevValue = JSON.parse(elm.dataset[prop]);
  const newValue = prevValue.concat(data);
  elm.dataset[prop] = JSON.stringify(newValue);
} 

pushElementToData(el, 'id', 2);
console.log(el.outerHTML)
<span id="el" data-id="[1]"></span>
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

I am not sure. Is this a good approach? But it updates attribute value.

When a new id arrives, you call the updateAttribute function.

const element = document.getElementById('el');

const updateAttribute = (_element, attr, val) => {
  updatedVal = JSON.parse(_element.getAttribute("data-id")).concat(val);
  _element.setAttribute("data-id", JSON.stringify(updatedVal)) ;
  console.log(_element)
} 

updateAttribute(el, 'data-id', 2);
<span id="el" data-id="[1]"></span>
Md Kawser Habib
  • 1,966
  • 2
  • 10
  • 25