0

I am dynamically changing the data-attribute of a couple of elements. An 'img' and an 'a' type. The 'img' element works with the following code:

$("img[data-image-index-no-"+self.options.typeOfImage+"="+nextIndexNo+"]").data("image-index-no-"+self.options.typeOfImage, newIndexNo);

I then wanted to change an 'a' link element and wrote:

$("a[data-slide-index="+nextIndexNo+"]").data("slide-index", newIndexNo);

The above didn't work but the I got it to work using:

$("a[data-slide-index="+nextIndexNo+"]").attr("data-slide-index", newIndexNo);

I would like to know why using the .data works with the img element but not the 'a' element? And which method is the preferred way?

Any ideas on this?

Huangism
  • 16,278
  • 7
  • 48
  • 74
John T
  • 1,078
  • 3
  • 14
  • 29

1 Answers1

2

When you fire a .data() method it tries to find data- element's attribute. If the attribute is non existent, the method won't work.

Similarly to that, .attr() also tries to find some specified element's attribute with one difference that if it can't find it, it will create it.

So, in your case, I'd guess that you're incrementing and trying to find an element with new nextIndexNo before actually updating that same element. As that element has the old nextIndexNo value, .data() method won't be able to find it, thus why .attr() works.

Glad I could point you in the right direction =)

Davion
  • 881
  • 6
  • 12