frosty
frosty

Reputation: 2649

insertAdjacentHTML wipes functions off page same as document.write

I had a previous question, and someone told me that document.write wipes all functions out, and to use insertAdjacentHTML instead, but when I tried it, it has the same result. The code still says that myFunction is not defined. What am I doing wrong?

// ==UserScript==
// @name         Replace Multiple Spaces With One Space
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       You
// @match        https://www.google.com/search?q=replaceSpace
// @grant        none
// ==/UserScript==

document.body.insertAdjacentHTML("beforeEnd", "<input type='text' id='myText' value='Some text...'>");
document.body.insertAdjacentHTML("beforeEnd", "<p id='demo'></p>");
document.body.insertAdjacentHTML("beforeEnd", "<button onclick='myFunction()'>Try it</button>");

function myFunction() {
  var string = document.getElementById("myText").value;
  string = string.replace(/\s\s+/g, ' ');
  document.getElementById("demo").innerHTML = string;
}

Upvotes: 1

Views: 251

Answers (1)

TimTIM Wong
TimTIM Wong

Reputation: 808

(function() {
    const myText = document.createElement("input"),
        demo = document.createElement("p"),
        button = document.createElement("button");
    myText.type = "text";
    myText.value = "Some text...";
    button.textContent = "Try it";
    button.addEventListener("click", () => demo.innerHTML = myText.value.replace(/\s{2,}/g, " "));
    document.body.insertAdjacentElement("beforeend", myText);
    document.body.insertAdjacentElement("beforeend", demo);
    document.body.insertAdjacentElement("beforeend", button);
})();

Upvotes: 1

Related Questions