Jackson Jackson - 1 year ago 51
Javascript Question

jQuery: create html elements from comma separated string?

I'm trying to create HTML elements (div's) from a comma separated string using jQuery.

Lets say I have a string that looks like this:

options ="some texts, another text, some more text";

and I need to create something like this:

<div>some texts</div>
<div>another text</div>
<div>some more text</div>

I first split the comma separated string like so:

var str = options;
var temp = new Array();
temp = str.split(", ");

And then I need to create the div's after this function which I have no idea how to do this.

Could someone please advise on this?


Try this:

var options ="some texts, another text, some more text";
var temp = options.split(", "); // first split string and convert it to array
var str = '';
$.each(temp, function(i,v) { // loop through array
  str += "<div>"+v+"</div>"; // create html string and store it in str variable
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>