Search code examples
javascriptaddeventlistenergetelementbyid

change title with a simple button


I can't fix this simple problem, I created a simple button and then a title which says "hello" .

If you press that button the text of the title should be changed for another text (any text I don´t care).

If I use jQuery it works perfectly, but I want to do this without jQuery just for learning.

document.querySelector(".btn").addEventListener("click", function() {
  document.querySelector("h1").innerHTML("hola como estas")
});
<h1 class="title">HELLO</h1>
<button class="btn" type="button"> Click me</button>

I use all the getElement and more and it doesn't work, it's supposed to change the text.


Solution

  • const btn = document.querySelector("button");
    const chngTxt = document.querySelector("h1");
    
    btn.addEventListener("click", function () {
        chngTxt.innerHTML = "hola como estas";
    })
    <h1>Hello</h1>
    <button id="changeText">click me</button>

    or you can just change your innerHTML to quotation mark

    document.querySelector(".btn").addEventListener("click", function(){
       document.querySelector("h1").innerHTML = "hola como estas";
    });