简体   繁体   中英

Display data on html template tag from javascript

I am trying to display data to html template tag from javascript. I can display the image from javascript to template but when i try the same thing in p tag, it gives me an error of TypeError: Cannot set property 'innerText' of null . Nothing is working, i tried using text/textContent/inner/innerHTML. Is there anything I am missing here?

index.html

<template id="product-template">
    <div class="col-sm-4">
      <div class="card border-light">
        <ul class="list-group list-group-flush">
          <li class="list-group-item"><img class="card-img-top" src="" id="product-img"></li>
          <li class="list-group-item"><p id="product-name">Name: </p></li>
          <li class="list-group-item"><p id="product-brand">Brand: </p></li>
          <li class="list-group-item"><p id="product-price">Price: </p></li>
          <li class="list-group-item"><p id="product-description">Description: </p></li>
        </ul>
      </div>
    </div>
</template>


<div class="container">
  <h1>Shop Online</h1>
  <div id="appRoot" class="row"></div>
</div>

script.js

const template = document.getElementById('product-template');
const card = document.querySelector('#appRoot');
length=8;
for(let index=0; index<length; index++){
  var clone = template.content.cloneNode(true);
  var image = clone.querySelector("li");
  var path = "/images/"
  image.querySelector("#product-img").src = path + data.imagepath;
  var name = clone.querySelector('p');
  name.querySelector('#product-name').innerText = data.name;
  card.appendChild(clone);

You might not need to query the p tag since you're picking them up by id anyway in the next line.

var name = clone.querySelector('p');
name.querySelector('#product-name').innerText = data.name;

That code looks to be looking for something like this, if you understand me:

<li class="list-group-item"><p><p id="product-name">Name:</p></p></li>

innerText is null because there's no tag with the id of "product-name" within a <p> tag.

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