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
JavaScript
x
9
1
<div id="updatable">
2
<q>{{QUOTE}}</q>
3
<br>
4
<h1>{{HEADING}}</h1>
5
<p>
6
My name is {{NAME}} and i am {{AGE}} yrs old . I love to play {{GAME}} and my hobbies include {{HOBBIES}} .
7
</p>
8
</div>
9
JS
JavaScript
1
56
56
1
class Template {
2
3
constructor(element, obj) {
4
this.element = element;
5
this.state = obj;
6
}
7
8
initState = function () {
9
this.element = document.querySelector(this.element);
10
this.#setState();
11
}
12
13
#setState() {
14
const obj = this.state;
15
Object.entries(obj).forEach(pair => {
16
this.element.innerHTML = this.element.innerHTML.replaceAll('{{'+ pair[0] +'}}', `<span data-var="${pair[0]}"> ${pair[1]} </span>`)
17
})
18
}
19
20
updateState = function (obj) {
21
Object.entries(obj).forEach(pair=> {
22
let key = pair[0]
23
let value = pair[1]
24
this.state[key] = value;
25
})
26
let template_elements = document.querySelectorAll('[data-var]');
27
template_elements.forEach(template_element => {
28
let attr = template_element.getAttribute("data-var");
29
template_element.innerText = this.state[attr];
30
})
31
32
}
33
}
34
35
36
const app = new Template("#updatable", {
37
QUOTE: "Coolest person in world ? ya that's me :-)",
38
NAME: "sanmeet",
39
GAME: "football",
40
HEADING: "About Me",
41
AGE: 19,
42
HOBBIES: "Coding and doing cool stuff",
43
});
44
45
// Initialize the functionality
46
app.initState()
47
48
// Updating variables
49
50
setTimeout(function() {
51
app.updateState({
52
GAME: "chess",
53
HEADING: "Really about me ! "
54
})
55
}, 2000);
56