Hello, the situation is as follows: there are two divs with the same id, they are in different parts of the document.

<div id="slider"></div> <div id="slider"></div> 

I need to add the first element to the first element, and the second to the second In order to get such a construction:

 <div id="slider" class="first"></div> <div id="slider" class="second"></div> 

How to implement it on jQuery?

  • @Igor sorry that not all jQuery experts. I offer my sincere apologies. - Ivan Vinokurov

2 answers 2

Such a $('#slider') selector with the same id on jQuery is impossible, you only get the first element. Here's a LifeHack $('[id="slider"]') looking through a tag.

 var obj = { 0: "first", 1: "second" }; $.each($('[id="slider"]'), function(i) { $(this).addClass(obj[i]); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="slider"></div> <div id="slider"></div> 

  • one
    the asterisk in the selector is not necessary; the id exactly matches - Grundy
  • @Grundy thanks removed - KYRAN

The id element property must be unique on the page. Here is the article . Either make different IDs for these elements, or do not use id at all and leave only the classes.

 <div class="slider first"></div> <div class="slider second"></div> 

If you need to select all slider-элементы use $('.slider') ; If any particular slider $('.slider.second') Read about jQuery selectors