javascript - How to change the child content of a div? -


i ran issue , unable "reach" child of 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 trying change background of div#board > div button.

i tried this:

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

but of course, doesn't work. tried various combinations nothing seems work. tips? (i have button calls function later that's not problem!)

this full code: https://jsfiddle.net/o72z8dqv/

update: solved, thanks! here updated working code.

you can use queryselectorall , need use loop change style of each child div because returns nodelist

function imagechange() {    var divs = document.queryselectorall("#board > div");    (var = 0; < 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 use array.from() or array.prototype.slice.call() , can use foreach loop


Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -