YING L
YING L

Reputation: 31

Add span tag to each element in an array in Javascript?

Suppose that I have an array. How can I wrap each element in the array in a span tag? Also, if I want to .appendchild each span element to a div element, how can I do it?

 function add_span(arr){  
     var new_arr= document.createElement("span");// arr is passed in correctly 
     var text=document.createTextNode(arr); // text cannot be output
     new_arr.appendChild(text);
     return new_arr;
 }

and in the main:

 for (i = 0; i < unique_array.length; i++)
 { 
     span_array[i]=add_span(unique_array[i]);
 }
 var cloud_text=document.createTextNode(span_array);
 cloud.appendChild(cloud_text);

the output now looks like this: [object HTMLSpanElement],[object HTMLSpanElement],[object HTMLSpanElement],[object HTMLSpanElement],[object HTMLSpanElement],[object HTMLSpanElement],[object HTMLSpanElement],[object HTMLSpanElement],[object HTMLSpanElement],[object HTMLSpanElement],[object HTMLSpanElement]

Upvotes: 0

Views: 5938

Answers (2)

DrRoach
DrRoach

Reputation: 1356

You want to loop through all of the array elements and add span tags to the beginning and end like so:

var example = [];

for(var i = 0; i < example.length; i++) {
    example[i] = '<span>' + example[i] + '</span>';
}

This adds the html span tags to your text and then your array element inside. The i acts as the identifier for which array object you are moifying.

Upvotes: 0

Xenyal
Xenyal

Reputation: 2223

JSFiddle Example (Updated)

Assume that you have an array of strings:

var arrayExample = ["apple", "orange", "pear"];

Iterate through each string within the array:

arrayExample.forEach(main);

Append the array string item into a span object, and then into a div object:

Edited

function main(arrayItem, index, array) {
    var spanObj = "<span>" + arrayItem + "</span>"
    var divObj = document.createElement('div');
    divObj.innerHTML = spanObj;

    // Do something like:
    document.body.appendChild(divObj);

    // Replace old array string with new array string wrapped in <span>
    arrayExample[index] = spanObj
}
alert(arrayExample); // will output your new Array 

Upvotes: 2

Related Questions