Hello I am new to this and I want to add the attribute data-gallery
to all the img
elements inside div#gallery-1
. How to do this using jQuery?
I have tried all of the answers but I get the "Uncaught TypeError: $ is not a function
" error. I am not a web developer but I want to know about that.
Thanks
Asked
Active
Viewed 1.1k times
-3

binary10
- 1
- 1
- 1
- 4
-
1Can you show what you have tried? Also, lots of examples out there: http://stackoverflow.com/questions/5995628/adding-attribute-in-jquery and this: http://stackoverflow.com/questions/11489037/add-and-remove-attribute-with-jquery – JGV Jul 19 '16 at 17:41
-
Check [Adding data attribute to DOM](http://stackoverflow.com/questions/14935191/adding-data-attribute-to-dom) – Mohammad Jul 19 '16 at 17:42
-
did you add a reference to jquery before your script? – Web pundit Jul 20 '16 at 08:54
-
@Webpandit yes of course there is a reference to jquery 1.12.4 – binary10 Jul 20 '16 at 10:32
3 Answers
5
No need to use each
or find
.
// set
$("#gallery-1 img").attr("data-gallery", "value");
// get
$("#gallery-1 img").attr("data-gallery");
You can even use data
. That is not an visible attribute in your code, it's stored in an jQuery object, but has the same effect.
// set
$("#gallery-1 img").data("gallery", "value");
// get
$("#gallery-1 img").data("gallery");

eisbehr
- 12,243
- 7
- 38
- 63
3
$("#gallery-1").find('img').each(function() {
$(this).attr('data-gallery', '');
})

Kilmazing
- 526
- 7
- 14
-
2Do we really need .each(function() for #gallery-1? #gallery-1 is an id and cannot be more than one in that page... – JGV Jul 19 '16 at 17:46
2
$("#gallery-1").find("img").attr("data-gallery", "");

underscore
- 6,495
- 6
- 39
- 78
-
1I think this is just a getter, for a setter you need to add a second param. – Kilmazing Jul 19 '16 at 17:44
-
1If you only set one parameter it will return the value in this attribute – Rene Limon Jul 19 '16 at 17:45
-