Home Change class of element in template
Reply: 0

Change class of element in template

user9231
1#
user9231 Published in September 20, 2018, 1:29 pm

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?

share|improve this question
  • You need to learn about scope. – jmargolisvt Nov 20 '17 at 13:59
  • stackoverflow.com/questions/195951/… – user8724929 Nov 20 '17 at 13:59
  • What do you mean? I'm trying to change the class name inside the addElement() function so it shouldn't be a problem or am I being slow here? – A.S.J Nov 20 '17 at 14:01
  • @SennerP this is not really relevant as I know how to change a class name generally, the problem is that I'm having trouble accessing the element whose name I want to change – A.S.J Nov 20 '17 at 14:04

1 Answer 1

active oldest votes
up vote 1 down vote accepted
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO