Intai'sei Intai'sei - 6 months ago 15
HTML Question

How to change the child content of a div?

I ran into an issue and I am unable to "reach" the child of this div:

<style type="text/css">
div#memory_board{
background:#CCC;
border:#999 1px solid;
width:800px;
height:540px;
padding:24px;
margin:0px auto;
}
div#memory_board > div{
background: url(http://image.png) no-repeat center;
border:#000 1px solid;
width:71px;
height:71px;
float:left;
margin:10px;
padding:20px;
font-size:64px;
cursor:pointer;
text-align:center;
}
</style>


What I am trying to do is change the background of all
div#board > div
with a button.

I tried this:

function imageChange(){
document.getElementsByTag("memory_board").style.background="url(http://image.png)";
}


But of course, it doesn't work. I tried various combinations but nothing seems to work. Any tips? (I do have a button which calls the function later so that's definitely not the problem!)

This is the full code:
https://jsfiddle.net/o72z8dqv/

UPDATE:
Solved, thanks!
Here is the updated working code.

Answer

You can use querySelectorAll and then you need to use loop to change style of each child div because it returns NodeList

function imageChange() {
  var divs = document.querySelectorAll("#board > div");
  for (var i = 0; i < divs.length; i++) {
    divs[i].style.backgroundImage = "url('http://placehold.it/350x150/333333')";
  }
}
div#board > div {
  background: url('http://placehold.it/350x150/ffffff') no-repeat center;
  border: #000 1px solid;
  width: 71px;
  height: 71px;
  float: left;
  margin: 10px;
  padding: 20px;
  font-size: 50px;
  text-align: center;
}
<button onclick="imageChange()">BUtton</button>
<div id="board">
  <div>Div</div>
  <div>Div</div>
</div>

You can also use Array.from() or Array.prototype.slice.call() and then you can use forEach loop

Comments