Goold eng
Goold eng

Reputation: 31

get attributes from document fragment?

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>

Upvotes: 0

Views: 1480

Answers (3)

Noah Camara
Noah Camara

Reputation: 21

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

Upvotes: 1

Aitor Solana
Aitor Solana

Reputation: 21

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

like this:

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

Upvotes: 0

mplungjan
mplungjan

Reputation: 177685

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>

Upvotes: 1

Related Questions