This question has already been answered:

How to replace:

document.write('<img src="' + window.Pic + 'Nickelback.jpg" height="311" width="400">'); 

So that the page is not erased?

Reported as a duplicate by Qwertiy , Sasha Omelchenko , ߊߚߤߘ , αλεχολυτ , Mikhail Vaysman on Apr 17 '17 at 0:09 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Tried it like this: document.getElementById ('pole'). InnerHTML = '<img src = "' + window.Pic + 'Nickelback.jpg" height = "311" width = "400">'; But chrome produces an error: (Uncaught TypeError: Cannot set property 'innerHTML' of null) - Gaara631
  • Place the script at the end of the document. In your case, javascript cannot find the element because it has not been created yet. - alvoro

4 answers 4

All options are correct: both appendChild, innerHTML, and insertBefore, but there is one BUT ... The browser interprets the code from top to bottom. When it reaches your javascript code, the required element does not exist yet . Try this:

 window.onload = function(){//Эта функция выполнится тогда, когда документ полностью загрузится var img = document.createElement('img'); img.src = window.Pic + 'Nickelback.jpg'; img.height = 311; img.width = 400; document.body.appendChild(img); } 
  • which element does not exist? document.body for sure. - woland

document.write always clears the page. this is his normal behavior. use dom-tree manipulations. Looking ahead, I’ll say that dom elements have an innerHTML property that might be useful to you.

     document.appendChild('<img src="' + window.Pic + 'Nickelback.jpg" height="311" width="400">') 
    • 2
      Hmm, I think you are mistaken. chrome agrees with me:> NotFoundError: Failed to execute 'appendChild' on 'Node': The new child element is null. javascript is not jquery. for what you want to show, you first need to create an element and then use innerHTML or outerHTML. - alvoro
    • 2
      var img = document.createElement ('img'); img.src = window.Pic + 'Nickelback.jpg; img.height = 311; img.width = 400; document.body.appendChild (img); - woland
     document.getElementById('element').appendChild(/* ваш элемент */) 

    also read about insertBefore , innerHTML , insertAdjacentHTML