SOLUTION: Uncaught TypeError: Cannot set property 'outerHTML' of null JavaScript Error

Updated on: June 14, 2021

If you are trying to access or modify the HTML element from JavaScript and getting error as: Uncaught TypeError: Cannot set property 'outerHTML' of null, then we need to verify below things in your HTML page and correct them if required:

SOLUTION: 

Run the application in the browser and right click on the browser page and click on Inspect or Open Developer Tools in the browser as shown in the below screenshot:

From the above screenshot in the Console tab, we can see, the error 'Uncaught TypeError: Cannot set property 'outerHTML' of null', because we are trying to set the outerHTML to an element which doesn't exist in the browsers DOM. This issue occurred when we clicked on the 'Change Content' button twice and in the first click, it replaced the outerHTML of div with id as 'outerHtmlElement' with new '<h4>' tag and now we don't have any div in the browser's DOM with id as 'outerHtmlElement', so it gave this error.  After the 'Change Content' button, our DOM will have following html structure which is as shown in the Elements tab in the below screenshot:

So, to resolve this error, we need to check whether an element exists in the Browser DOM, if yes, then only we can get and set these properties (such as innerHTML, outerHTML, innerText, outerText)  on an element.

Below HTML code shows proper way of checking and then setting any property to an element:

  1. <html>
  2. <head><title>innerText Test Application</title>
  3. </head>
  4. <body style="text-align:center;margin:20px;">
  5. <div id="outerHtmlElement"><h4>outerHTML Element</h4></div>
  6. <div><input type="button" onclick="ChangeContent();" value="Change Content"/></div>
  7. <script>
  8. function ChangeContent() {
  9.     var outerHtmlElm = document.getElementById('outerHtmlElement');
  10.     if(outerHtmlElm){
  11.         outerHtmlElm.outerHTML = '<h4>Outer HTML Element Content is Changed</h4>';
  12.     }
  13. }
  14. </script>
  15. </body>
  16. </html>

Sometimes, we also get error as : 'Uncaught DOMException: Failed to set the 'outerHTML' property on 'Element': This element has no parent node.', so this error also has the same fix as shown above to check whether an element exists in the DOM, if yes, then only get/set any property of an element.