1

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>');
1
  • 1
    What have you tried so far? Commented Jun 18, 2021 at 19:36

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

PS: value is an absolutely valid attribute on a OL > LI element, reintroduced in HTML5 - but only valid in the scope of an <ol> (Ordered List) parent.
1

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);

Comments

1

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.