简体   繁体   中英

Convert string to HTML element using JavaScript or jQuery

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

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

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM