Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an id on an element created from a template element

I have a template element that I use to create <li>-Elements on my page. I can set the textContent attributes of the inner elements of that template. However I can not set the id for the parent element inside the template.

<template id="list-item">
  <li class="list-group-item">
    <div class="media-body">
      <strong class="list-item-text"></strong>
      <p class="list-item-text"></p>
    </div>
  </li>
</template>

<div id="output"></div>

And this is the required js to demonstrate the issue.

var template = document.querySelector('#list-item');
var listItem = document.importNode(template.content, true);
var lines = listItem.querySelectorAll('.list-item-text');

lines[0].textContent = 'title';
lines[1].textContent = 'description';
listItem.id = 5;

document.querySelector('#output').appendChild(listItem);

Text contents will be set correctly, however the id won't be set at all (the js attribute gets created but it does not appear in the DOM.

I also created a jsfiddle for this.

How can I set the id of the newly appended element? My current approach is to avoid templates in general and use strings in order to construct the element, which makes me feel dirty.

like image 706
Selim Avatar asked Aug 18 '16 16:08

Selim


2 Answers

The problem is that you are trying to handle a document-fragment (listItem) as an DOM element. Instead, you should first get/query the element from the document-fragment as follows:

var docFragment = document.importNode(template.content, true);
var listItem = docFragment.querySelector('li');

See working JSFiddle

Also, see documentation about DocumentFragment here.

like image 61
leo.fcx Avatar answered Oct 05 '22 08:10

leo.fcx


You need to use listItem.querySelector() on the document-fragment and change the id then:

listItem.querySelector("li").id = 5;

var template = document.querySelector('#list-item');
var listItem = document.importNode(template.content, true);
var lines = listItem.querySelectorAll('.list-item-text');

lines[0].textContent = 'title';
lines[1].textContent = 'description';
listItem.querySelector("li").id = 5;
document.querySelector('#output').appendChild(listItem);
like image 43
baao Avatar answered Oct 05 '22 08:10

baao