Search code examples
javascriptfor-loopdominnerhtml

Changing the H1 with for loop in JavaScript


JS newbie here. I am trying to get all the values in an H1 tag and change the ones have lower than 4 lengths.

It says "Please Answer the Questions" I need it to say "Please answer Hello Questions"

let header = document.getElementById("h1").innerHTML;
let splittedText = header.split(" ");

function seperateText() {
  for (let i = 0; i < splittedText.length; i++) {
    if (splittedText[i].length < 4) {

      splittedText[i].innerHTML = "Hello"
    }
  }
  // console.log(splittedText[i]);
  return splittedText[i].innerHTML;
}
seperateText();
<h1 id="h1">Please Answer the Questions</h1>


Solution

  • Your code is trying the set innerHTML of a string - that does not work

    Also the [i] does not exist outside the loop

    Try this map

    const seperateText = str => {
      let splittedText = str.split(" ");
      return splittedText.map(word => word.length > 4 ? word : "hello").join(" ");
    }
    
    let header1 = document.getElementById("h1")
    header1.innerHTML = seperateText(header1.innerHTML);
    
    let header2 = document.getElementById("empty")
    header2.innerHTML = seperateText(header2.innerHTML);
    <h1 id="h1">Please Answer the Questions</h1>
    <h1 id="empty"></h1>

    or this replace

    const seperateText = str => {
      return str.replace(/\b(\w+)\b/gi, match => match.length < 4 ? "hello" : match);
    }
    
    let header1 = document.getElementById("h1")
    header1.innerHTML = seperateText(header1.innerHTML);
    
    let header2 = document.getElementById("empty")
    header2.innerHTML = seperateText(header2.innerHTML);
    <h1 id="h1">Please Answer the Questions</h1>
    <h1 id="empty"></h1>