简体   繁体   中英

Javascript - Check if div element exists by id

 const d = document.getElementById("added"); if (d) { d.innerHTML = "Test2"; } else { d = document.createElement("div"); d.innerHTML = "Test3"; document.body.appendChild(d); }
 <div id="added_2">Test1</div>

I want to check if a div element exists. If yes, then change its innerHTML property, else create it with some other innherHMTL . I use the above code and it works if the div already exists but otherwise it gives the error Javascript - Check if div element exists by id ...

You defined d as const, so you can't overwrite it. Use let instead and you should be OK:

 let d = document.getElementById("added"); if (d) { d.innerHTML = "Test2"; } else { d = document.createElement("div"); d.innerHTML = "Test3"; document.body.appendChild(d); }
 <div id="added_2">Test1</div>

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