<body> <div class="wrapper"> </div> </body>
const createDOMFromSring = domstring => { const div = document.createElement("div"); div.innerHTML = domstring; return div; }; class UpVoteButton { constructor() { this.state = { isUpVoted: false }; } setState(state) { const oldElem = this.elem; this.state = state; this.elem = this.render(); if (this.onStateChange) this.onStateChange(oldElem, this.elem); } changeUpVotedText() { this.setState({ isUpVoted: !this.state.isUpVoted }); } render() { this.elem = createDOMFromSring(` <button class='upvote-btn'> <span class='upvote-text'>${ this.state.isUpVoted ? "Cancel" : "UpVote" }</span> <span><i class="fa fa-thumbs-up" aria-hidden="true"></i></span> </button> `); this.elem.addEventListener("click", this.changeUpVotedText.bind(this)); return this.elem; } } class DownVoteButton { constructor() { this.state = { isDownVoted: false }; } setState(state) { const oldElem = this.elem; this.state = state; this.elem = this.render(); if (this.onStateChange) this.onStateChange(oldElem, this.elem); } changeDownVotedText() { this.setState({ isDownVoted: !this.state.isDownVoted }); } render() { this.elem = createDOMFromSring(` <button class="downvote-btn"> <span class="downvote-text">${ this.state.isDownVoted ? "Cancel" : "Downvote" }</span> <span><i class="fa fa-thumbs-down" aria-hidden="true"></i></span> </button> `); this.elem.addEventListener("click", this.changeDownVotedText.bind(this)); return this.elem; } } // as render() method now returns an Object of HTMLDivElement // it cannot be appended like innerHTML, instead use DOM // API to append it const wrapper = document.querySelector(".wrapper"); const upVoteButton = new UpVoteButton(); wrapper.appendChild(upVoteButton.render()); upVoteButton.onStateChange = (oldElem, newElem) => { wrapper.insertBefore(newElem, oldElem); wrapper.removeChild(oldElem); }; const downVoteButton = new DownVoteButton(); wrapper.appendChild(downVoteButton.render()); downVoteButton.onStateChange = (oldElem, newElem) => { wrapper.insertBefore(newElem, oldElem); wrapper.removeChild(oldElem); };