0

I have an HTML template that I wrote; which is this:

<div class="secret">
            <p class="title secret-title">built in HTML</p>
            <div class="secret-message locked">
                <p class="text-inside">locked</p>
            </div>
            <button class="hack">hack</button>
        </div>

I want to add this template to my index.html page using JavaScript with javaScript's innerHTML property but, the problem is; I want to edit this HTML template in javaScript before rendering it, the code i wrote is here:

class Secret {
    constructor(title, typeOfSecret) {
        this.title = title
        this.typeOfSecret = typeOfSecret
    }

    secret = `<div class="secret">
            <p class="title secret-title">${this.title}</p>
            <div class="secret-message ${this.typeOfSecret}">
                <p class="text-inside black">${this.typeOfSecret}</p>
            </div>
            <button class="hack">hack</button>
        </div>`
    

    append() {
        //console.log(this.secret)
        console.log(this.secret)
        elementsContainer.innerHTML += this.secret
    }

}

The problem is that it returns UnDefined at the places i use ${this.typeOfSecret} and {this.name} like this: the undefined picture

So how to add this to make the user able to add his own data to the website?

Note: I know this stuff because I'm a python guy but I'm stuck with JavaScript so I have no problem with a complicated answer

julien.leroux5
  • 969
  • 7
  • 17

1 Answers1

0

The way you defined the "secret" made it a class variable, similar to this in Python

class Secret:

    secret = f"{self.type_of_secret}"

    def __init__(self, type_of_secret):
        self.type_of_secret = type_of_secret

And when you goto visit secret, it won't have access to self

If you really want to access it without calling a method, you can consider using a getter, this is similar to @property in python. See below.

class Secret {
    constructor(title, typeOfSecret) {
        this.title = title
        this.typeOfSecret = typeOfSecret
    }

    get secret() {
      return `<div class="secret">
            <p class="title secret-title">${this.title}</p>
            <div class="secret-message ${this.typeOfSecret}">
                <p class="text-inside black">${this.typeOfSecret}</p>
            </div>
            <button class="hack">hack</button>
        </div>`
    }

    appendTo(elementsContainer) {
        // In your example, it didn't have elementsContainer defined, I assume you have it in a higher scope?
        console.log(this.secret);
        elementsContainer.innerHTML += this.secret
    }

}

x = new Secret("secret title", "typeofsecret"); // don't forget to `new` here
x.appendTo(document.querySelector("#x"));
<div id="x"></div>
rabbit.aaron
  • 2,369
  • 16
  • 25