5

I made an each function that counts the images inside a div and I am trying to set the number of images counted inside the div as a data attribute for the div but it is not working.

Have I gone about this the wrong way because it does not seem to be working?

Here is the site http://www.touchmarketing.co.nz/test/

    var mostImages = 0;

    numSliders = $wowSlides.length,
    lastVindex = numSliders-1;

    $wowSlides.each(function(){

        var $this = $(this),
        $images = $this.find('img'),
        numImages = $images.length;

        $images.css({width:$slideWidth, 'float':'left', 'position':'relative'}).wrapAll('<div class="slider" />');
        $slider = $this.find(".slider");
        $slider.width($slideWidth*numImages).css({'float':'left'});                     

        $this.data('count', numImages); // add data-count="insert number here" to this .wowSlides div

        console.log(numImages); 

        if(numImages > mostImages){

            mostImages = numImages;

        }                   

    });
1
  • What do you mean by not working? FYI, setting .data() on an element via jQuery will not show as data- attributes in the source. Commented Feb 20, 2013 at 23:00

1 Answer 1

16

This sets data to jQuery's proprietary data cache:

$this.data('count', numImages);

It doesn't set to a data- attribute of the element. Generally there shouldn't be a need to set a data- attribute on the client, since its purpose is to transfer data from server to client.

Nevertheless, if you want to set it, use

$this.attr('data-count', numImages)

or

this.setAttribute('data-count', numImages)

Personally, if I wanted to associate a small amount of data with an element, I'd just store it as a property directly on the element itself.

this.count = numImages;

For primitive data, it's harmless. For larger objects or other DOM elements, I'd be more hesitant.

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

Comments

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.