If I understand your question right, you want your H1
to always have the value as a variable in your JS. Even when the variable is changed.
For this, you might need certain restrictions on how you create the variable. This answer here Listening for variable changes in JavaScript will be able to help you.
I've modified that a bit with more meaningful variables.
var watchableVariable = {
originalVal: null,
valListener: function(val) {},
set val(val) {
this.originalVal = val;
this.valListener(val);
},
get val() {
return this.originalVal;
},
registerListener: function(listener) {
this.valListener = listener;
}
}
watchableVariable.registerListener(function(val) {
setH1Val(val);
});
var setH1Val = function(val){
document.getElementById('the-title').innerText = val;
}
watchableVariable.val = 'Hey!';
setH1Val(watchableVariable.val)
setTimeout(function(){
watchableVariable.val = 'Hello!';
}, 4000);
and the HTML
<h1 id="the-title"></h1>
Note: Even after this, there is a chance that someone might be able to change the text of the h1
using other JavaScript methods. If you want to avoid that, you might want to look into MutationObserver
.