0

I want to access the data-index attribute in javascript but when I type taskElement.dataset.index I am getting an error

How can I access the attributes that in the template element?

const tasksContainer = document.querySelector('[data-tasks]')
const taskTemplate = document.getElementById('task-template')
const taskElement = document.importNode(taskTemplate.content, true)
tasksContainer.appendChild(taskElement)
<div class="tasks draggables-container" data-tasks>Tasks:</div>

<template id="task-template">
  <div class="task draggable" draggable="true" data-index>
    <input type="checkbox" />
    <label>
      <span class="custom-checkbox">Text</span>
    </label>
  </div>
</template>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Goold eng
  • 21
  • 1
  • 1
  • 2

3 Answers3

1

You can access the attributes of elements in a DocumentFragment by querySelecting for them and then accessing them the normal way you would.

taskElement.querySelector("div[data-index]").dataset.index

0

You mean this?

const tasksContainer = document.querySelector('[data-tasks]')
const taskTemplate = document.getElementById('task-template')
const taskElement = document.importNode(taskTemplate.content, true)
console.log(taskElement.querySelector("div[data-index]").dataset.index)
tasksContainer.appendChild(taskElement)
<div class="tasks draggables-container" data-tasks>Tasks:</div>

<template id="task-template">
  <div class="task draggable" draggable="true" data-index="idx">
    <input type="checkbox" />
    <label>
      <span class="custom-checkbox">Text</span>
    </label>
  </div>
</template>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

You need to assign value to dataset tags to access it.

like this:

<div class="task draggable" draggable="true" data-index="1">