I have array
0: ['a', 'n', 'i', 'm', 'a', 'l']
1: ['c', 'a', 'r']
2: ['f', 'l', 'o', 'w', 'e', 'r']
I want to wrap each array into html element. for example
<div><span>c</span><span>a</span><span>r</span></div>
<div><span>a</span><span>n</span><span>i</span><span>m</span><span>a</span><span>l</span></div>
How can I achieve this using jQuery?
You can use Array.prototype.map .
You want to map over the outer array so that each element is converted to:
`<div>${element}</div>`
And map the inner array so that each element is converted to:
`<span>${element}<span>`
You can use vanilla JS also.
var arr = [
["a", "n", "i", "m", "a", "l"],
["c", "a", "r"],
["f", "l", "o", "w", "e", "r"]
];
let html = "";
arr.forEach((letters) => {
html += "<div>";
letters.forEach((l) => {
html += `<span>${l}</span>`;
});
html += "</div>";
});
I think you have an array contain object as you mentioned in the question. You could use for loop to loop the array and use appendTo
.
let array =[{ 0: ['a', 'n', 'i', 'm', 'a', 'l'], 1: ['c', 'a', 'r'], 2: ['f', 'l', 'o', 'w', 'e', 'r'], }] for(let i =0;i<Object.keys(array[0]).length;i++){ for(let j =0;j<Object.values(array[0])[i].length;j++){ $("<span>"+Object.values(array[0])[i][j]+"</span>").appendTo('body'); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
const input = [ ['a', 'n', 'i', 'm', 'a', 'l'], ['c', 'a', 'r'], ['f', 'l', 'o', 'w', 'e', 'r'] ]; for (let i in input) { console.log('<div><span>' + input[i].join('</span><span>') + '</span></div>'); }
You can use
let arr = [
["a", "n", "i", "m", "a", "l"],
["c", "a", "r"],
["f", "l", "o", "w", "e", "r"]
];
let text = "";
$.each(arr, function(i, e) {
text += "<div>";
$.each(e, function(key, val) {
text += "<span>" + val + "</span>";
});
text += "</div>";
});
$( "body" ).append( text );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.