简体   繁体   中英

How can I write each character from string to separate div using JavaScript?

This is what I have been far

This is my code:

function createWordTiles() {
            var word = ['Example'];
            var innerDiv;

            var iDiv = document.createElement('div');
            iDiv.id = 'tileBlock';
            iDiv.className = "tileBlock";

Code works only i remove loop :

            for (var l = 0; l <= word.length ; l++) {

                innerDiv = document.createElement('div');
                innerDiv.id = 'Block' + l;
                innerDiv.className = 'Block';
                innerDiv.innerHTML = word.charAt(l);
            }

            iDiv.appendChild(innerDiv);

            document.getElementsByTagName('body')[0].appendChild(iDiv);
        }

This is what I have made

How can I write each character from string to separate div using JavaScript?

Move your iDiv.appendChild(innerDiv); inside the for loop, like this:

for (var l = 0; l <= word.length ; l++) {

    innerDiv = document.createElement('div');
    innerDiv.id = 'Block' + l;
    innerDiv.className = 'Block';
    innerDiv.innerHTML = word.charAt(l);

    iDiv.appendChild(innerDiv);
}

HTML

<div class="container">
    <p class="source-text">Hello world</p>
</div>
<ul class="list"></ul>

js

jQuery(document).ready(function($) {
var sourceText = $('.source-text').text(); // get the source text
var $destinationElm = $('.list'); // get destination 

var i;
for(i = 0; i < sourceText.length; i++) {  // eterate through all characters
    $destinationElm.append('<li>' + sourceText[i] + '</li>'); // appends html element with text
}});

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