stack
stack

Reputation: 10228

How to join the values of two array plus some html code between them?

I have these two arrays:

var numbers = ['one',  'two', 'three'];
var colors  = ['blue', 'red', 'white'];

Now I want this output:

$('.classname').html("<span id = 'one'>blue</span><span id = 'two'>red</span><span id = 'three'>white</span>");

How can I do that?


I can use join and mix second array with <span> but I cannot add id={arr1-values}:

$('.classname').html('<span>' + colors.join('</span><span>') + '</span>');

Upvotes: 1

Views: 72

Answers (5)

Nick
Nick

Reputation: 156

This is what you need:

var numbers = ['one',  'two', 'three'];
var colors  = ['blue', 'red', 'white'];

$.each(numbers, function(k, number) {
  $('.classname').append("<span id='"+ number +"'>"+ colors[k] +"</span>");
});

https://jsbin.com/tobozuliya/edit?html,js,output

Upvotes: 1

Oriol
Oriol

Reputation: 288100

If you want to avoid HTML injection, don't concatenate strings like that. Use DOM methods instead:

var numbers = ['one',  'two', 'three'],
    colors = ['red', 'green', 'blue'],
    target = document.querySelector('.classname');
target.innerHTML = ''; // Remove previous contents
numbers.forEach(function(id, i) {
  var el = document.createElement('span');
  el.id = id;
  el.textContent = colors[i];
  target.appendChild(el);
});
#one { color: red }
#two { color: green }
#three { color: blue }
<div class="classname"></div>

Upvotes: 5

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

It's better if you could use an object to make the relation between the two arrays e.g:

var colors = {one: 'blue', two: 'red', three: 'white'}

Then you can loop through the object and append the spans to the element :

$.each(colors, function(index,value){
    $('.classname').append("<span id="+index+">"+value+"</span>");
})

Hope this helps.


var colors = {one: 'blue', two: 'red', three: 'white'}

$.each(colors, function(index,value){
    $('.classname').append("<span id="+index+">"+value+"</span>");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="classname"></div>

Upvotes: -1

Jagdish Idhate
Jagdish Idhate

Reputation: 7742

Assuming colors and numbers are of same length, one liner.

numbers.map(function(elm,index){
  return '<span id='+elm+'>'+colors[index]+'</span>'
}).join();

As suggested by @mmm it would be better to have in object like

{
 number:'one'
 color:'blue'
}

Upvotes: 0

MysterX
MysterX

Reputation: 2368

Try to build HTML by iterating arrays:

var numbers = ['one',  'two', 'three'];
var colors  = ['blue', 'red', 'white'];
var resultHTML = '';
for(var i = 0; i < numbers.length; i++){
  resultHTML += '<span id = "'+ numbers[i] + '">' + colors[i] + '</span>'
}

$('.classname').html(resultHTML);

Upvotes: 1

Related Questions