-1

Is it possible to use .addClass to each item with a specific ID? I have 2 gallery containers, and both needs to have a class added. They do both have the same id #galleri_container. When trying this: $('#galleri_container').addClass('active'); It only affects number 1 in that list, (the first #galleri_container). I need it to affect both number 1 and number 2.

How to achieve the desired effect?

Magnus Pilegaard
  • 393
  • 2
  • 4
  • 17
  • Possible duplicate of [How to select all elements with a particular ID in jQuery?](http://stackoverflow.com/questions/902839/how-to-select-all-elements-with-a-particular-id-in-jquery) – Michał Perłakowski Jan 22 '16 at 08:54

4 Answers4

1

It's wrong to have multiple elements share an ID. It's against the standard and causes unexpected behavior. Always use unique IDs in HTML - and only use IDs when you actually need them. Use a different selector for your elements (probably a CSS class).

Amit
  • 45,440
  • 9
  • 78
  • 110
0

You can't have multiple elements with the same ID in HTML. Use classes instead.

$(".galleri_container").addClass(".active");
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
0

It is not a good practice to use same id to more than one element. The javascript or jquery will effect only the first element because it finds the first element in from the DOM tree.

Please check this link:

https://softwareengineering.stackexchange.com/questions/127178/two-html-elements-with-same-id-attribute-how-bad-is-it-really

Community
  • 1
  • 1
Prudhvi Konda
  • 297
  • 1
  • 7
0

According to html standard, id has to be unique. If you want same styles for multiple components, you should use a class instead.

So instead of using something like this:

<div id="galleri_container">
<div id="galleri_container">

Change the id's to class

<div class="galleri_container">
<div class="galleri_container">

and where ever you're using #galleri_container, replace that with .galleri_container.

This means that you can now use the jquery's .addClass as you wanted in the first place.

Marko Gresak
  • 7,950
  • 5
  • 40
  • 46