Search code examples
javascripthtmldomgoogle-chrome-extension

onclick not working chrome expention JS HTML dom


trying to inject html to website and activeat button using the onclick function

const locetion = document.querySelector("#app > div:nth-child(1)"); // set the locetion on the website for the injection
var div = document.createElement('div'); 
div.innerHTML = '<input type="search" id="mySearch" placeholder="Search for something..">';

let btn = document.createElement("button");
btn.onclick = function () {
  alert("Button is clicked");

};
btn.innerHTML = "Save";
btn.setAttribute('id','123123')
locetion.append(div);
locetion.append(btn);

locetion.append(div); --> document.body.appendChild(div) work just fine

Solution

  • It's possible that the locetion variable isn't being set correctly, or there might be an issue with the selector you're using to target the element. You can try using console.log(locetion) to see if it's correctly selecting the element you want.

    Also, make sure that the script is running after the element has loaded on the page. You can wrap your code in a DOMContentLoaded event listener to ensure that the script runs after the page has fully loaded, like this:

        document.addEventListener("DOMContentLoaded", function(event) {
      const locetion = document.querySelector("#app > div:nth-child(1)"); 
      var div = document.createElement('div'); 
      div.innerHTML = '<input type="search" id="mySearch" placeholder="Search for something..">';
    
      let btn = document.createElement("button");
      btn.onclick = function () {
        alert("Button is clicked");
      };
      btn.innerHTML = "Save";
      btn.setAttribute('id','123123')
      locetion.append(div);
      locetion.append(btn);
    });
    

    Also, there's a typo in locetion. It should be location.