Can't change HTML content successfully

The problem is that the the text within <em> tags changes after the script is executed but I don’t know why the text within <p> tags disappear.

<body>

	<div id = "p1">
		<p> Hello World! </p>
		<em> Chu Chu </em>
	</div>

	<script>
		document.getElementById("p1").innerHTML = "<em> New text! </em>";
	</script>

</body>

Because you’re selecting on the element with the id p1 then overwriting all it’s contents with innerHTML.

Add an id to the element who’s content you want to update.

<div id = "p1">
    <p> Hello World! </p>
    <em id="p2"> Chu Chu </em>
</div>
document.getElementById("p2").innerHTML = "New text!";
2 Likes

Thank you very much!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.