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
You need to use the
content
property to access content of the template.The
dataset
property is for accessingdata-
html attributes and would be followed with the name of the attribute, as indataset.category
. As the error states,querySelector()
is not a valid method on the data object returned from thedataset
property.