Selim Selim - 11 months ago 41
HTML Question

Setting an id on an element created from a template element

I have a template element that I use to create

-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 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'; = 5;


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.

Answer Source

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.