Marius
Marius

Reputation: 2008

Convert string to Array of letters and then output each SPAN

I'm trying to convert a string into Array of letters but only using JavaScript (no jQuery)

For now I have worked this out but I know I'm missing more, I know there are jQuery for this but I want to learn more about vanilla JS

function myFunction() {
    var str = 'Test';
    var split = str.split("");
    document.getElementById('demo').innerHTML = '<span class="test">' + split + '</span>';
}
myFunction()

Upvotes: 0

Views: 1198

Answers (4)

AndrewL64
AndrewL64

Reputation: 16301

You can do this in just one-line by spreading your string characters to an array and then map through the array, pushing each character "e" wrapped in the span tag to your #demo div element using the innerHTML property like this:

[...str].map(e => document.getElementById('demo').innerHTML += `<span class="test">${e}</span>`;

Check and run the following Code Snippet for a practical example of the above:

/* JavaScript */
function myFunction(str) {
    [...str].map(e => document.getElementById('demo').innerHTML += `<span class="test">${e}</span>`
)}

myFunction("Test");
myFunction("Hello");
/* CSS */
.test {display: block; background-color: green; margin: 5px 0px;text-align:center; font-size: 20px;}
<!-- HTML -->

<div id="demo"></div>

Upvotes: 0

ellipsis
ellipsis

Reputation: 12152

Try this

function myFunction() {
    var str = 'Test';
    var split = str.split('');
      split.forEach((e)=>{
   var span= document.createElement("span"); 
   var textnode = document.createTextNode(e);
   span.appendChild(textnode);document.getElementById("demo").appendChild(span); 
    })

}
myFunction()

Check the fiddle

Upvotes: 1

antonku
antonku

Reputation: 7665

You can construct the required html string by mapping each letter to a span element and then joining the result:

function myFunction() {
    var str = 'Test';
    var split = str.split("");
    document.getElementById('demo').innerHTML = split.map(letter => `<span class="test">${letter}</span>`).join('');
}
myFunction()
<div id="demo"></div>

Upvotes: 1

Amin Jafari
Amin Jafari

Reputation: 7207

You are so close to the answer, you only need to iterate over the array:

function myFunction() {
    var str = 'Test';
    var split = str.split("");
    var html = '';
    for(let i = 0; i < split.length; i++) {
        html += '<span class="test">' + split[i] + '</span>';
    }
    document.getElementById('demo').innerHTML = html;
}
myFunction()

Upvotes: 1

Related Questions