I want to split a string value in a single digits and wrap()
it in <li></li>
. I am trying to achieve this goal but fail to do this following is my code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(e) { var str = $('#number').html(); var spl = str.split(''); var len = spl.length; var i = 0; setInterval(function() { if (i <= len) { $('#number').wrap('<li>' + spl[0] + '</li>') } i++; }, 200) }) </script> <div id="number">123456 as</div>
<script>
$(document).ready(function(e) {
var str = $('#number').html();
var spl = str.split('');
var len = spl.length;
var i = 0;
setInterval(function(){
if(i <= len )
{
$('#number').append('<li>'+spl[i]+'</li>')
}
i++;
},200)
})
</script>
reference append
here spl[0]
this always selects the first index of array (split)... use spl[i]
try this
var str = $('#number').html();
var spl = str.split('');
var len = spl.length;
var i = 0;
setInterval(function () {
if (i < len) {
if (spl[i] != " ") { //checking for the space here
$('#number').append('<li>' + spl[i] + '</li>')
//-^^^^^^----------^^^^^^-----here
}
}
i++;
}, 200)
If you're trying to move each character from the text into a <li>
, then here's an alternative solution that splits the text nodes in place and wraps them:
//- Get a reference to the raw text node
var txt = $('#number').contents()[0];
setTimeout(function repeat(){
if (txt.nodeValue.length) {
//- Split the text node after the first character
txt = txt.splitText(1);
//- txt is now the latter text node, so wrap the former with a <li>
$(txt.previousSibling).wrap('<li>');
//- Rinse and repeat
setTimeout(repeat, 200)
}
},200);
Also, I swapped your setInterval
for a setTimeout
because your timer would have run indefinitely, whereas this stops when the sequence is complete.
Here's one splitting backwards for fun:
var txt = $('#number').contents()[0];
setTimeout(function (){
if (txt.nodeValue.length) {
$(txt.splitText(txt.nodeValue.length - 1)).wrap('<li>');
setTimeout(arguments.callee, 200)
}
},200);
See also:
try this:
var str = $('#number').html();
var spl = str.split('');
var len = spl.length;
var i = 0;
setInterval(function(){
if(i <= len )
{
if(spl[i] !== undefined && spl[i] !== " "){
$('#number').wrap('<li>'+spl[i]+'</li>')
}
}
i++;
},200);
working fiddle here: http://jsfiddle.net/n5Brh/1/
DO NOT wrap with html content only html tag is allowed in wrap()
here is your ans jsfiddle
$(document).ready(function(e) {
var str = $('#number').html();
var spl = str.split(' ');
var len = spl.length;
var i = 0;
if(i <= len )
{
$('#number').wrap('<li id="dd"> </li>')
}
i++;
$('#number').text(spl[0]);
})
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.