Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get element from document.importNode?

I have a template that I'm cloning in an iteration by document.importNode. What I can not do is to add a class to the cloned element.

var t = document.querySelector('#template');
var clone = document.importNode(t.content, true);
document.querySelector('#target').appendChild(clone);
clone.classList.add('glyphicon glyphicon-search'); // error thrown here, classList is undefined

What is a cloned node exactly? The console it says it is a #document-fragment. How can I get the created element from the clone without using querySelector and indexing the cloned nodes?

The template looks like this one:

<template id="template">
    <div class="row">
        <div class="col-xs-3 no"></div>
        <div class="col-xs-6 no2"></div>
        <div class="col-xs-3 quantity"></div>
    </div>
</template>
like image 426
Perrier Avatar asked Aug 06 '15 11:08

Perrier


1 Answers

Cloning a <template>'s content will indeed give you a document fragment. This is not a element attached to the DOM, but a lightweight wrapper which contains a set of DOM elements - so it doesn't have properties like classList.

You must query the contents of the document fragment, before it's appended to the DOM, like so:

var t = document.querySelector('#template');
var clone = document.importNode(t.content, true);
// Make any modifications to the clone now
clone.querySelector(".row").classList.add('glyphicon', 'glyphicon-search');
//                          ^^ Note the corrected syntax for classList.add too
document.querySelector('#target').appendChild(clone);
<template id="template">
    <div class="row">
        <div class="col-xs-3 no">No</div>
        <div class="col-xs-6 no2">No2</div>
        <div class="col-xs-3 quantity">Qty</div>
    </div>
</template>
<div id="target">
    
</div>

Results in the following markup:

<div id="target">
    <div class="row glyphicon glyphicon-search">
        <div class="col-xs-3 no">No</div>
        <div class="col-xs-6 no2">No2</div>
        <div class="col-xs-3 quantity">Qty</div>
    </div>
</div>
like image 145
CodingIntrigue Avatar answered Oct 19 '22 06:10

CodingIntrigue