1

I have an array

var arr = [3,0,1,0,0];

and multiple divs.

<div class="fb0"></div>
<div class="fb1"></div>
<div class="fb2"></div>
<div class="fb3"></div>
<div class="fb4"></div>

and more.

How to add values from an array alternately by numbers in an array to div numbers by classes.

<div class="fb0">3</div>
<div class="fb4">0</div>
<div class="fb2">1</div>
<div class="fb3">0</div>
<div class="fb1">0</div>
2
  • You can use .each() method. jQuery('[class^=fb]').each(function(idx){ if(arr.length >= idx) // check if the array length is grater/equal to the current index. jQuery(this).text(arr[idx]); }); Commented Feb 17, 2019 at 7:14
  • I don't get why in the second block of HTML the div elements have been reordered into different positions? Is there any logic to that? Commented Feb 17, 2019 at 7:21

2 Answers 2

3

You can use jQuery's .each() to loop through all the div. Inside event handler function use the index to take the item from the array and set the text of the current element:

var arr = [3,0,1,0,0];

$('[class^=fb]').each(function(idx){
  if(arr.length >= idx) // check if the array length is grater/equal to the current index.
    $(this).text(arr[idx]);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fb0"></div>
<div class="fb1"></div>
<div class="fb2"></div>
<div class="fb3"></div>
<div class="fb4"></div>

JavaScript solution with Document.querySelectorAll() and Array.prototype.forEach():

var arr = [3,0,1,0,0];
var elements = [].slice.call(document.querySelectorAll('[class^=fb]'));
elements.forEach(function(div, idx){
  if(arr.length >= idx) // check if the array length is grater/equal to the current index.
    div.textContent = arr[idx];
});
<div class="fb0"></div>
<div class="fb1"></div>
<div class="fb2"></div>
<div class="fb3"></div>
<div class="fb4"></div>

Sign up to request clarification or add additional context in comments.

Comments

2

You can use querySelectorAll to select the div's and than using forEach you can add the values to each div accordingly.

function update(){
  let arr = [3,0,1,0,0];
  let divs = document.querySelectorAll('[class^=fb]')
  divs.forEach((e,i)=>{
    e.innerHTML = arr[i]
  })

}
<div class="fb0"></div>
<div class="fb1"></div>
<div class="fb2"></div>
<div class="fb3"></div>
<div class="fb4"></div>
<button onClick=update()>Click me to see output</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.