get attributes from document fragment?

1.2k Views Asked by At

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>

3

There are 3 best solutions below

0
mplungjan On

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>

0
Aitor Solana On

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

like this:

<div class="task draggable" draggable="true" data-index="1">
0
Noah Camara On

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