简体   繁体   中英

HTML template - assigning html data

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 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM