-1

For this segment of code:

 for (var i = 0; i < numbers.length; i++) {
 var imageCrystal = $('<img>');
 imageCrystal.attr('data-num', numbers[i]);
 ....
 }

is, imageCrystal.attr('data-num', numbers[i]); making a data attribute for the image tag that was just created and giving it a class name called "data-num" and then assigning whatever the value is at number[i]?

Sushanth --
55.8k9 gold badges70 silver badges109 bronze badges
asked Oct 14, 2016 at 22:42
10
  • 1
    attr creates an attribute in the element. Attributes prefixed with data- are an HTML5 thing for storing data in the element. So if numbers[i] was 3, this would make an imageCrystal element that looks like <img data-num="3" />. Data attributes can also be accessed using the jQuery data function, so imageCrystal.data("num") should return 3. Commented Oct 14, 2016 at 22:46
  • 1
    Worth noting here that the last line can be written as imageCrystal.data('num', numbers[i]); also if you use the data() method. Commented Oct 14, 2016 at 22:47
  • @DavidG haha, just added my edit right as you posted that. Commented Oct 14, 2016 at 22:48
  • ahh I got it. Thank you for the clarification. I am new to jquery and it is totally different from c++ syntax. Is there a place where I can look up jquery attributes like 'data'? For example, I didnt even know the data() function could be set in the html tags directyl using the jquery atrribute. Commented Oct 14, 2016 at 22:59
  • isnt that creating a new img element? Also, I have an click function after this where $('.crystalImage').on( 'click', function() { counter = counter + parseInt($(this).data('woohoo')); Commented Oct 14, 2016 at 23:05

1 Answer 1

5

Simply put

imageCrystal.attr('data-num', numbers[i]); is a setter

imageCrystal.attr('data-num'); is a getter

If var numbers = [100, 200, 300] and if the img tags are appended to the DOM, it would look something in these lines.

<img data-num="100" />
<img data-num="200" />
<img data-num="300" />

More info: http://api.jquery.com/attr/

answered Oct 14, 2016 at 22:44
Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the clarification also. I am new to jquery and am still trying to understand the syntax of jquery.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.