0

I want to replace an element and the text in the element inside it with js code. But when I try this I get an error. This is because element 2 is inside element 1. But I need to use it this way and I couldn't find a solution. If you look at the sample code below, you will understand what I mean. Thank you from now.

HTML Code:

<div id="element_1">Test Div
 <p id="element_2">Test Paragraph</p>
</div>

JS Code:

document.getElementById("element_1").innerHTML = "New Div Text";
document.getElementById("element_2").innerHTML = "New Paragraph Text";

Result HTML:

<div id="element_1">New Div Text
  <p id="element_2">{empty}</p>
</div>

Error is:

Uncaught TypeError: Cannot set property 'innerHTML' of null
İsa C.
  • 329
  • 5
  • 16
  • 2
    When you do this `document.getElementById("element_1").innerHTML = "New Div Text";` your setting the innerHTML to just that plain text and destroying the nested `

    ` content. Therefore it is indeed not on the DOM and null.

    – Tanner Dolby Aug 04 '21 at 18:25
  • 1
    See https://stackoverflow.com/questions/4106809/how-can-i-change-an-elements-text-without-changing-its-child-elements – chesscov77 Aug 04 '21 at 18:28
  • 2
    Does this answer your question? [How can I change an element's text without changing its child elements?](https://stackoverflow.com/questions/4106809/how-can-i-change-an-elements-text-without-changing-its-child-elements) – chesscov77 Aug 04 '21 at 18:28
  • 1
    @Juan - Good find! I should have realized this was well-covered... :-) – T.J. Crowder Aug 04 '21 at 18:31
  • 1
    Thanks a lot guys. Here is the question and solution. I found it because of you. I just didn't know how to ask. I tried and it works. Thanks again. Cheers! – İsa C. Aug 04 '21 at 18:44

0 Answers0