Reputation: 11394
When I add a sibling div to the #boundary div, I can no longer change the style of the #box child div. What am I doing wrong? The following is a simplified version of my code:
let box = document.getElementById("box");
let boundary = document.getElementById("boundary")
//Adding this line prevents my code from changing the #box style to blue
boundary.innerHTML += "<div>A</div>"
document.addEventListener("keydown", function(event) {
if (event.key == "ArrowDown") {
box.style.backgroundColor = "blue"
}
})
#box {
width: 75px;
height: 75px;
background-color: green;
border: solid black 1px;
position: absolute;
top: 100px;
left: 100px;
}
<div id="boundary">
<div id="box"></div>
</div>
Upvotes: 1
Views: 59
Reputation: 191976
Adding a string to innerHTML
creates a new #box DOM element, and this breaks the box
reference in your code. Use Element.insertAdjacentHTML()
instead:
let box = document.getElementById("box");
let boundary = document.getElementById("boundary")
boundary.insertAdjacentHTML( 'beforeend', "<div>A</div>");
document.addEventListener("keydown", function(event) {
if (event.key == "ArrowDown") {
box.style.backgroundColor = "blue"
}
})
#box {
width: 75px;
height: 75px;
background-color: green;
border: solid black 1px;
position: absolute;
top: 100px;
left: 100px;
}
<div id="boundary">
<div id="box"></div>
</div>
Another option is to remove the let box = document.getElementById("box");
line. This will work because every element with id
creates an automatic global variable, that references it and updates automatically.
let boundary = document.getElementById("boundary")
boundary.innerHTML += "<div>A</div>";
document.addEventListener("keydown", function(event) {
if (event.key == "ArrowDown") {
box.style.backgroundColor = "blue"
}
})
#box {
width: 75px;
height: 75px;
background-color: green;
border: solid black 1px;
position: absolute;
top: 100px;
left: 100px;
}
<div id="boundary">
<div id="box"></div>
</div>
Upvotes: 1
Reputation: 272965
When you append a new string to innerHTML it's like you create a new HTML content inside #boudary
so the old element you selected is different from the new one created.
To verify this, select your element after the DOM change and you will get the new one created and you will be able to change its style:
let boundary = document.getElementById("boundary")
boundary.innerHTML += "<div>A</div>";
//Here you select the new one
let box = document.getElementById("box");
document.addEventListener("click", function(event) {
box.style.backgroundColor = "blue"
})
#box {
width: 75px;
height: 75px;
background-color: green;
border: solid black 1px;
position: absolute;
top: 100px;
left: 100px;
}
<div id="boundary">
<div id="box"></div>
</div>
Upvotes: 2
Reputation: 45
You need to put a semicolon after it.
boundary.innerHTML += "<div>A</div>";
I hope this helps.
Upvotes: -1