How do i display a text anywhere on a html page
I want to achieve something like this
Example
{{title}} // there will be more than one like this one
If something like this is available anywhere on the page it should display ”This is the title” so if i change the “This is the title” the {{title}} should also change
I know don’t know much about this but i guess this is possible with javascript
Advertisement
Answer
HTML
<div id="updatable"> <q>{{QUOTE}}</q> <br> <h1>{{HEADING}}</h1> <p> My name is {{NAME}} and i am {{AGE}} yrs old . I love to play {{GAME}} and my hobbies include {{HOBBIES}} . </p> </div>
JS
class Template { constructor(element, obj) { this.element = element; this.state = obj; } initState = function () { this.element = document.querySelector(this.element); this.#setState(); } #setState() { const obj = this.state; Object.entries(obj).forEach(pair => { this.element.innerHTML = this.element.innerHTML.replaceAll('{{'+ pair[0] +'}}', `<span data-var="${pair[0]}"> ${pair[1]} </span>`) }) } updateState = function (obj) { Object.entries(obj).forEach(pair=> { let key = pair[0] let value = pair[1] this.state[key] = value; }) let template_elements = document.querySelectorAll('[data-var]'); template_elements.forEach(template_element => { let attr = template_element.getAttribute("data-var"); template_element.innerText = this.state[attr]; }) } } const app = new Template("#updatable", { QUOTE: "Coolest person in world ? ya that's me :-)", NAME: "sanmeet", GAME: "football", HEADING: "About Me", AGE: 19, HOBBIES: "Coding and doing cool stuff", }); // Initialize the functionality app.initState() // Updating variables setTimeout(function() { app.updateState({ GAME: "chess", HEADING: "Really about me ! " }) }, 2000);