Home Change class of element in template
Reply: 1

Change class of element in template

A.S.J
1#
A.S.J Published in 2017-11-20 13:55:16Z

I have an html template which, on click on a button, I clone and append to a div. I want to change the class name of a div which is nested inside the template, however, I do not know how. I tried looking it up but I couldn't find any way to do that in JavaScript, the only posts I found were about Visual Studio Code etc, however, as mentioned, I want to do this in JavaScript.

The template look something like this:

<template id="newElement">
    <div class="wrapper">
        <p>Test Paragraph</p>
    </div>
</template>

This is how I clone and append the template:

function addElement() {

    var listElement = document.getElementById('newElement');
    var cloneTemplate = listElement.content.cloneNode(true);
    var list = document.getElementById("list");
    list.appendChild(cloneTemplate);
    cloneTemplate.removeAttribute("id");

}

Now, I want to change the class of the newly generated element. I tried this using:

cloneTemplate.content.className = "newName";
cloneTemplate.className = "newName";

I also tried accessing the div inside the template and changing its class, however, I keep getting the error message that the element I try to access is undefined. Does anyone know how I could fix this?

DKSan
2#
DKSan Reply to 2017-11-20 14:17:49Z

If you log the content of var cloneTemplate you will receive something like this: DocumentFragment [ #text, div.wrapper, #text ]

Selecting the div.wrapper by var div = cloneTemplate.querySelector( 'div.wrapper' ); and changing its class to div.className = 'newName'; will result in your desired output.

Put together in your function:

function addElement() {
    var listElement = document.getElementById('newElement');
    var cloneTemplate = listElement.content.cloneNode(true);

    var div = cloneTemplate.querySelector( 'div.wrapper' );
    div.className = 'newName';

    var list = document.getElementById("list");
    list.appendChild(cloneTemplate);
}

Removed cloneTemplate.removeAttribute("id"); because it throws an error and your cloned content does not contain any id's.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.297269 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO