Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Split and loop in array

Featured Replies

In this post Lindsey sent awesome script for loop. And it works perfect. I always play with this script when i try to use loop. Now i go deeper in js and i see that when i try to use this script with split function i see the different result. Maybe i should convert array members in real object? Please, provide me advice what's the different between array members and object like id or class and how i should implement split array result into loop?

 

jsfiddle

<div id="random">Hello world</div>
<span id="result"></span>

.red {
    color:red;
}

jQuery(document).ready(function ($) {

   var splitText = $('#random').text().split("");
    
    /*
    function run(i) {
    splitText.removeClass('red').eq(i).addClass('red');
    setTimeout(function() {
        run(i+=1);

    }, 1000);
}
run(0);
 */
             document.getElementById("result").innerHTML = splitText;
   
    });

What is it you're trying to do exaclty? Your wrapping jQuery function is wrong. You have the $ sign as a parameter but you pass nothing in as an argument. To send jQuery as a parameter and Alias it to the $ sign you can do this with an IIFE like the example below:


(function($){

}(jQuery);

Then for the document ready you can use a shorthand, using the aliased jQuery parameter $. It will execute when the DOM ready event fires.

(function($){
  $(function(){

    // this code will execute one document is read
    // and $ is aliased to jQuery function.

  });
}(jQuery);

In this line

document.getElementById("result").innerHTML = splitText;

you may as well use jQuery seen as you've already loaded it, no need to combine jQuery and the normal DOM API really.

$('#result').html(splitText);

In your code you are using recursion to keep calling your run function. This is not strictly a loop but can have similar results. The split method you use creates an Array. To loop through an array you are best off using a for loop. For loops were design to deal with arrays. This code, won't benefit from objects.

Edited by rbrtsmith

  • Author

Thank you a lot for pointing on my jQuery wrapping mistake! About innerHTML... I was confused after reading Addy Osmany slides. Look at slide 70 of 121. He said that its better to use innerHTML and i noticed that you use innerHTML in your script.

About for loop i agree on 100%. I started from this but failed))

 

I did the following:

(function($){

   var splitText = $('#random').text().split("");
    
    for (var i = 0, i < splitText.length; i++) {

$('#result').html(splitText[i]);
       
}
      
      }(jQuery);

Created new fiddle I wanted to achive this result.

 

 

(function ($) {

    var splitText = $('#random').text().split("");
    // splitText is an Array of Strings.


    /**
    / Iterate through Array, wrap each String in a span
    / and append to #result.
    */
    splitText.forEach(function (ltr) {
        $('<span/>', {
            text: ltr
        }).appendTo($('#result'));
    });

    function run(i) {
        $('#result span').removeClass('red').eq(i).addClass('red');
        setTimeout(function () {
            run(i += 1);
        }, 1000);
    }
    run(0);
})(jQuery);

http://jsfiddle.net/60zm48gd/

  • Author

Fantastic! Awesome construction i never seen this before. Wynn, thank you a lot. If possible, provide a little explanation about span wrapper. What "," means in this. text: ltr - this is object name/value? And this stroke $('<span/>', with comma (,) is used special for wrapper this object?

Edited by fleur

 

Thank you a lot for pointing on my jQuery wrapping mistake! About innerHTML... I was confused after reading Addy Osmany slides. Look at slide 70 of 121. He said that its better to use innerHTML and i noticed that you use innerHTML in your script.

About for loop i agree on 100%. I started from this but failed))

 

I did the following:

(function($){

   var splitText = $('#random').text().split("");
    
    for (var i = 0, i < splitText.length; i++) {

$('#result').html(splitText[i]);
       
}
      
      }(jQuery);

Created new fiddle I wanted to achive this result.

 

 

 

 

I haven't yet seen the thing by Addy, I am making the assumption that he wasn't using jQuery and so he was just using vanilla JS to work with the DOM. As far as I am aware, under the hood jQuery's html method uses innerHTML, both doing the same thing: setting or returning the HTML that it is called on.

 

@@Wynn I wasn't aware that you could pass in an object as a second parameter to the jQuery function, thanks for making me aware!

Edited by rbrtsmith

  • Author

I see. I used to read sidebar. Its always up to date. Please, tell me what does comma "," do here. Just the name of construction. I will google this for to learn deeper. I was very impressed.

It's a shorthand method of creating a jQuery object.

'<div/>' is short for '<div></div>'. the comma is just a separator between parameters. The second parameter is an object literal containing the data you want to apply to the element.

eg.

$('<div/>', {
    'class': 'value',
    id: 'foo',
    text: 'this is a div',
    css: {
        background: 'black',
        color: 'white',
        height: '50px',
        padding: '1rem'
    },
    on: {
        click: function () {
            $(this).css('background', 'blue');
        }
    }
});

http://jsfiddle.net/nofdzg5x/

Class is a reserved word, so must be wrapped in quotes.

Edited by Wynn

It's a shorthand method of creating a jQuery object.

 

'<div/>' is short for '<div></div>'. the comma is just a separator between parameters. The second parameter is an object literal containing the data you want to apply to the element.

 

eg.

$('<div/>', {
    'class': 'value',
    id: 'foo',
    text: 'this is a div',
    css: {
        background: 'black',
        color: 'white',
        height: '50px',
        padding: '1rem'
    },
    on: {
        click: function () {
            $(this).css('background', 'blue');
        }
    }
});

http://jsfiddle.net/nofdzg5x/

 

Class is a reserved word, so must be wrapped in quotes.

 

 

Ok, So we're just creating a new jQuery object rather than selecting one from the DOM. Makes sense now :). I always thought they had bad intentions reserving the word 'class' now it's all apparent with the release of ES6.

Edited by rbrtsmith

  • Author

Wonderful script! Wynn, thank you a lot for incredibly useful information!

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.