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>