简体   繁体   中英

Unable to add content using insertAdjacentHTML after i have successfully removed it

this is my code:

 "use strict"; const searchBox = document.querySelector("#myText"); const searchBtn = document.querySelector(".btn-search"); const searchContainer = document.querySelector(".search-container"); let mainText = document.querySelector(".main-text"); const quit = document.querySelector("#btn-close"); let showMain; const newMain = ""; let printMain = function(text) { showMain = ` <article class="country"> <h1>Country you Searched</h1> <p>Hello</p> <p>${text}</p> </article>`; console.log(`Our show main is: ${showMain}`); mainText.insertAdjacentHTML("beforeend", showMain); }; searchBox.addEventListener("click", function() { if (searchBox.value === "Type in") { searchBox.value = ""; } }); searchBtn.addEventListener("click", function() { if (searchBox.value && searchBox.value.== "Type in") { console.log(searchBox;value). printMain(searchBox;value). searchBox;value = ""; } else { alert("please type in country name;"). } }), quit.addEventListener("click"; function() { //mainText.remove(showMain); const myDiv = document.getElementById("myId"); const parent = myDiv.parentNode; parent.removeChild(myDiv); console;log(showMain); });
 <,DOCTYPE html> <html lang="en"> <header> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <script defer src="script:js"></script> <title>Simple Work</title> <button id="btn-close">go back</button> </header> <body> <main class="container"> <div class="main-text" id="myId"></div> <p class="search-container"> <label>Type In : </label> <input type="text" id="myText" value="Type in" /> </p> <button class="btn-search">input</button> </main> </body> </html>

So, I was trying to make code that add the text using insertAdjacentHTML and next when I click "go back" button, it will erase the html that I had added using insertAdjacentHTML. I have success up to this point. After this when I try to add new HTML using insertAdjacentHTML, it doesn't work. What I must do to fix this?

(as my English is second language, explanation might not be clear, I am just making web site that I could add text(must use insertAdjacentHTML) and erase that by using "go back" button and after I erase all of them, it could add new text again by using "input" button)

When you remove the node, you are removing the element that mainText points to, therefore, you code cannot place content into a node that is no longer there. So it throws an error stating so.

You should probably only remove the element with classname of country :

document.querySelector('.country').remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM