Reputation: 567
I have a string like this:
i1:1,i3:5,i2:5
How can I convert it to a HTML element like this using pure JavaScript or jQuery?
<ul>
<li id="i1" value="1"></li>
<li id="i3" value="5"></li>
<li id="i2" value="5"></li>
</ul>
What I have tried so far:
document.write('<ul>i1:1,i3:5,i2:5</ul>');
Upvotes: 1
Views: 1031
Reputation: 63589
split
the initial string on the comma, then map
over the resulting array. On each iteration of map
you can then split on the colon, and return a HTML string. You just need to make sure you join
the array that map
returns into a new string before you add it to the DOM.
const str = 'i1:1,i3:5,i2:5';
const result = str.split(',').map(el => {
const [key, value] = el.split(':');
return `<li id="${key}" value="${value}">${value}</li>`;
}).join('');
const ol = document.querySelector('ol');
ol.insertAdjacentHTML('beforeend', `<ul>${result}</ul>`);
<ol />
Additional documentation
Upvotes: 3
Reputation: 2810
With jQuery:
function createUlListByString(myString) {
var elements = myString.split(',');
var ul = $('<ul>');
elements.forEach(function(item) {
item = item.split(':');
var li = $('<li id="' + item[0] + '" value="' + item[1] +'">'+ item[1] + '</li>');
ul.append(li);
});
return ul;
}
var ul = createUlListByString('i1:1,i3:5,i2:5');
Vanilla JavaScript:
function createUlListByString(myString) {
var elements = myString.split(',');
var ul = document.createElement('ul');
elements.forEach(function(item) {
item = item.split(':');
var li = document.createElement('li');
li.id = item[0];
li.value = item[1];
ul.append(li);
});
return ul;
}
var ul = createUlListByString('i1:1,i3:5,i2:5');
Upvotes: 1
Reputation: 15223
I believe that my simple solution using method forEach()
and method split()
will not be superfluous, which will split the string into an id and a value taken from an array of similar data.
let ul = document.createElement("ul");
document.body.appendChild(ul);
["i1:1", "i3:5", "i2:5"].forEach(function (li) {
let id_value = li.split(":");
ul.innerHTML += "<li id=" + id_value[0] + ">" + id_value[1] + "</li>";
});
console.log(ul.outerHTML);
Upvotes: 1