0

I am trying to grab the attributes on certain selection tags like so:

$('tagName').swapper();

Each section has like data-image="source", I need to grab each of these and create an array out of it. Here is where I am stuck, I can get each one individually, but not all at once to create the array, below is my code for the array creation.

var imgArray = [];
        $this.each(function() {
            var count = getImgAttr.length;
            imgArray.push([getImgAttr]);
            console.log(imgArray);
            console.log(count);
        });

getImgAttr is just $this.data("image");

This returns each one as an individual array, not one combined.

How would I connect all of them and prevent them from being split?

Thanks guys.

2
  • why are you wrapping it in []? you should be defining getImgAttr for each image you are iterating over, otherwise it will only ever look at the first image. Commented Feb 19, 2014 at 21:29
  • How I completely drop that? I will give it a shot, this was formatted from the jQuery API site, so I am trying to figure out how to do this correctly. And I just took it off, now it grabbing the correct information. Now it is a matter of merging the 3+ that I have. Commented Feb 19, 2014 at 21:33

1 Answer 1

1

Your problem is likely coming from here:

var getImgAttr = $this.data("image");

this gets the data atttribute value of the first element in the collection within $this. You should be doing this inside of the area where you are iterating over the images. Also, you can simplify the code by skipping the each and going to .map.

$.fn.swapper = function(){
    var imageArr = this.map(function(){
        return $(this).data("image");
    }).get();
    console.log(imgArr);
    return this;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This worked, thanks! It is grabbing each one individually, now it is just reapplying and randomizing the content for each one. Thank you again!

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.