Jamgreen
Jamgreen

Reputation: 11039

Get data attributes from object in list in JavaScript

I have a list of objects

[Object, Object, Object]

Each objects has

Object {x: 1, y: 0, width: 4, height: 5, max_width: undefined…}

and some other parameters. Each object is a <div> element with data attributes <div id="panel" data-panel-id="2">. How can I get the value of data-panel-id?

I have tried

items.forEach(function (item) {
  console.log(item);
  console.log(item.el);
  console.log(item.el.firstNode);
  console.log(item.el.firstNode.dataset);

etc.

I think it would work if I used document.getElementById("panel").dataset.panelId but my list contains objects and not html elements, so I don't know how to do it.

My list of objects is created from gridstack.js library (https://github.com/troolee/gridstack.js) in an onChange listener.

Upvotes: 0

Views: 1539

Answers (1)

Rama Rao M
Rama Rao M

Reputation: 3051

I never worked on this library but I just checked the library and found that every item object has it's DOM node in el attribute. So we can data set following way:

    items.forEach(function (item) {
     var panelId =  item.el[0].dataset['panelId'] //el[0] --> Since el is a jQuery object we need to get it's javascript object.

     //If you want to use jQuery:
     var panelId =  item.el.data('panelId');
    }

Upvotes: 1

Related Questions