0

So let's say I make a h1, ok?

I want to make it's value always set to... let's say "x".

How do I do this, I've tried with a while true loop, but that just crashes the site.

How is this doable, if it is?

[please don't give me dislikes for no reason, I'm just new here]

Technot
  • 60
  • 7

3 Answers3

0

First of all, you need to define HTML first and then JS, and no need to use while(true). It will go forever, instead run once and replace it as it won't get change in the future.

var x = "Text setted form JS - To this";

function myFunc() {
  document.getElementById("h1").innerHTML = x;
  // or
  // document.getElementById("h1").textContent = x;
}
myFunc();
<h1 id="h1">
  This should change to x forever
</h1>

YOUR CODE AND MISTAKES

<html>
<script> // DEFINING JS FIRST
  var x = ("To this")
  function myFunc() {
    document.getElementById("h1").innerHTML = x; //HERE document.getElementById("h1") will be null
  }
  while (true) { // INFINITE LOOP
    myFunc()
  }
</script>
<h1 id = "h1">
  This should change to x forever
</h1>
</html>
DecPK
  • 24,537
  • 6
  • 26
  • 42
0

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.

Green Wizard
  • 3,507
  • 4
  • 18
  • 29
0

on html : <h1 id=solve>lorem</h1> on js : var x = document.getElementById("solve").textContent; u can view it console.log(x);

mourshad
  • 21
  • 2