1

I am trying to create an array with only the attribute data-id of each elements but getting an undefined array. What am I doing wrong ?

The declaration: var list = [...document.querySelectorAll("#selection > tr")].map(el => el["data-id"]);

The elements:

<tbody id="selection">
  {% for form in formset %}
    <tr data-id={{form.instance.id}}>
    </tr>
  {% endfor%}
</tbody>

thank you

4
  • 1
    use getAttribute("data-id") Commented Apr 21, 2020 at 6:34
  • Excellent, thank you ! Commented Apr 21, 2020 at 6:36
  • i've put it as an answer Commented Apr 21, 2020 at 6:37
  • Datasets might be more appropriate, e.g. element.dataset[keyname] (or el => el.dataset.id in your case) Commented Apr 21, 2020 at 6:39

2 Answers 2

2

data-* attributes are accessed in JS code using .dataset.* (in your case .dataset.id)

final code should be

var list = [...document.querySelectorAll("#selection > tr")].map(el => el.dataset.id);

check out data-*

Sign up to request clarification or add additional context in comments.

Comments

1

var list = [...document.querySelectorAll("#selection > tr")].map(el => el.getAttribute("data-id"));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.