1

I can't seem to make this work and I've tried many different combinations. All I want to do is get characters four and five from text returned from an .each() iterator before writing it to an array.

    var timeItems = [];
    $("div[class*='field-name-field-time-']").each(function (i, e) {
        $(this).text().slice(3,5);
        timeItems.push($(e));
    });

Any ideas?

Thanks!

1
  • Ok , is your text located inside like this <element>text</element> and do you want to push element or text to timeItems, because currently you just take it and store it nowhere Commented Jul 14, 2016 at 18:03

2 Answers 2

1

Try this

var timeItems = [];
$("div[class*='field-name-field-time-']").each(function (i, e) {

    var text = $(e).text().substring(3,5); //Dont forget to store them somewhere
    timeItems.push($(e));
});

.slice() should also work. Check the JSFiddle below and uncomment the line that uses slice to try it out.

Also what are you returning to the array? I'm assuming you mean the object but if you want to return the characters, you should push text to timeItems instead of $(e).

EDIT: https://jsfiddle.net/nv5tfszw/4/

Sign up to request clarification or add additional context in comments.

Comments

0
var timeItems = [];
$("div[class*='field-name-field-time-']").each(function (i, e) {
    var text = $(e).text().slice(3,5);
    timeItems.push(text);
});
  1. Try using second argument from each parameter instead of this.
  2. Assign your slice to a variable and return to push. (http://www.w3schools.com/jsref/jsref_slice_string.asp)

The question is often raised, "If this is the element, why is there a second DOM element argument passed to the callback?" Whether intentional or inadvertent, the execution context may change. When consistently using the keyword this, it's easy to end up confusing ourselves or other developers reading the code.

https://learn.jquery.com/using-jquery-core/iterating/#the-second-argument

2 Comments

can you provide me a codepen/plunkr of your problem? codepen.io
Thanks, Stefan, your solution worked, but I couldn't get the string because it changed position when it was written to the array. Works well now. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.