A little confusion with Node.replaceChild()

Hello everyone, I have a question about the Node.replaceChild().
Below there’s a trivial code that replaces the h1 element with another one (I know I could have changed the text with innerHTML, I’m just trying out the new concepts I’m learning) with a different text. Now, it works, but the new element is not targeted by the CSS rules; as you can see I’ve tried to target just the tag, and it doesn’t work; then I’ve tried to add an id to the new child and target that one: no results, just plain text. Anyone can help me please? I’d like to understand what’s wrong with my code. Thanks in advance!

<style>
  #random{
    background: #111;
 color: green;
 padding: 10px;
  }
h1{
 background: #111;
 color: green;
 padding: 10px;
}
 button {
    margin-left: 40%;
    margin-top: 10px;
    padding: 10px;
    font-size: 25px;
    border-radius: 2px;
    box-shadow: 2px 2px 1px blue, -2px -2px 1px red;
    cursor: pointer;
    font-family: monospace;
    font-weight: 800;
    color: #ff4dff;

  }
   button:hover{
    background: #111; 
    opacity: .8;
  }
</style>

<div class='ciao'>
<h1>This title will be changed</h1>
<button>Test me</button> 
</div>

<script>  
  document.getElementsByTagName('button')[0].addEventListener('click', function(){
  let parent = document.getElementsByTagName('h1')[0].parentNode
  let child = document.getElementsByTagName('h1')[0]
  let newChild = document.createElement('h1').appendChild(document.createTextNode('Hello World'))
  newChild.id = 'random'
  parent.replaceChild(newChild, child) 
  })
</script>

Hi @doriodavid. I think your problem is in the line below:

let newChild = document.createElement('h1').appendChild(document.createTextNode('Hello World'))

According to MDN, appendChild returns the appended child. For example if you invoke it like element.appendChild(aChild), it returns aChild which is 'Hello World' for your case and you are assigning it to newChild. Essentially you are replacing the h1 element with the text 'Hello World'. If you click the button the second time, you get an error because there is no h1 element any more. Try using the devTool after clicking the button once. You will see what I am talking about. You will remove the error if you do the following:

let newChild = document.createElement('h1');
let textNode = document.createTextNode('Hello World');
newChild.appendChild(textNode);