Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Gemini Brain
Gemini Brain
13,817 Points

Listening for onclick event issue

Hi, I'm facing an issue with listening for onclick event of newly created element. In short, I'm trying to create a new section element every time I click on its button so it creates a new section sibling.

Firstly, I initialize default section:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Creating elements</title>
</head>
<body>
<div id="wrapper"></div>
<script src="wrapper.js"></script>
</body>
</html>
// wrapper.js
import {Section} from "./section.js"

class Wrapper extends Section {
    constructor() {
        super();
        this.wrapper = document.getElementById("wrapper")
    }

    initialize() {
        this.wrapper.appendChild(this.addSection())
    }
}
const wrapper = new Wrapper();
wrapper.initialize()
// section.js
import {Container} from "./container.js"

export class Section extends Container {
    constructor() {
        super();
    }

    addSection() {
        const newSection = document.createElement("section")
        newSection.appendChild(this.addContainer())
        newSection.innerHTML += this.addSectionButton()
        newSection.querySelector(`.btn-new-section`).addEventListener("click", (e) => {
            this.addSection()
        })
        return this.wrapper.appendChild(newSection)
    }

    addSectionButton() {
        return `<button type="button" class="btn-new-section">New section</button>`;
    }
}

So far, it works fine. But part of each section element is creation of another element "div.container" and this element has its own listener that does not work on click so it does not create container siblings within the section.

// container.js
export class Container {
    addContainer() {
        let newContainer = document.createElement("div")
        newContainer.classList.add(`container`)
        newContainer.innerHTML += this.addContainerButton()
        newContainer.querySelector(`.btn-new-container`).addEventListener("click", (e) => {
            this.addContainer()
        })
        return newContainer
    }

    addContainerButton() {
        return `<button type="button" class="btn-new-container">New container</button>`;
    }
}

Any help how handle this issue? Thank you.