HTML template - assigning html data

866 Views Asked by At

I am using HTML for the first time in combination with an AJAX call. Is it possible assign html data to a div using JavaScript?

I have the following:

<template class="template result student">
    <div class="result student" data-category="student">
        <div class="box name">
            <span class="name">John Smith</span>
            <br />
            <span class="category">Student</span>
        </div>
    </div>
</template>

And JS

const studentTemplate = 
    document.querySelector(".template.result.student"),
    category = studentTemplate.dataset.querySelector(".result.student"),
    studentName = studentTemplate.content.querySelector(".box.name .name"),
    date = studentTemplate.content.querySelector(".box.dob .date");

   category.textContent    = "student";
   studentName.textContent = "student name";

So as you can see I am trying to set date-student in the template via JS. But I get

studentTemplate.dataset.querySelector is not a function

Question is, what is correct way of doing this? Setting the content works fine

1

There are 1 best solutions below

0
On

You need to use the content property to access content of the template.

The dataset property is for accessing data- html attributes and would be followed with the name of the attribute, as in dataset.category. As the error states, querySelector() is not a valid method on the data object returned from the dataset property.

const studentTemplate = document.querySelector(".template.result.student");
var category = studentTemplate.content.querySelector(".result.student");
var studentName = studentTemplate.content.querySelector(".box.name .name")
var dte = studentTemplate.content.querySelector(".box.dob .date");

// Modify the text content of the elements
category.textContent    = "teacher";
studentName.textContent = "teacher name";

// Modify the data-category attribute value of the the div
category.dataset.category = "teacher";
console.log(category);
<template class="template result student">
    <div class="result student" data-category="student">
        <div class="box name">
            <span class="name">John Smith</span>
            <br />
            <span class="category">Student</span>
        </div>
    </div>
</template>