Mohammed
Mohammed

Reputation: 457

find second id of the same id jquery

I have a little issue with elements having the same ID name in a sharepoint solution.

I am trying to add a class to the div using jquery:

HTML:

<div id="DeltaPlaceHolderMain">
    <a id="mainContent" name="mainContent" tabindex="-1"></a>
    <div style="padding-left:5px">

If i write this Jquery line in the console:

$('#DeltaPlaceHolderMain');

I don't get the div that I want to add the class to because there are multiple #DeltaPlaceHolderMain id.

So my question is how do i select only the second #DeltaPlaceHolderMain using jquery?

Upvotes: 0

Views: 3084

Answers (3)

Paul Brown
Paul Brown

Reputation: 1

Of course IDs have to be unique, but sometimes this out of your control, when you're working with 3rd parties, who are unwilling to change the code, or they have to wait for a deployment. Thank you to those that provided a solution until the IDs can be changed!

Upvotes: 0

emmanuel
emmanuel

Reputation: 9615

Ids must be unique. In case you can't change that, you could use [att=val] selector.

$('#DeltaPlaceHolderMain').addClass('selected');

$('[id=\'DeltaPlaceHolderMain2\']').addClass('selected');
.selected { background: orange; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="DeltaPlaceHolderMain">
  <a id="mainContent" name="mainContent" tabindex="-1">1</a>
  <div style="padding-left:5px"></div>
</div>
<div id="DeltaPlaceHolderMain">
  <a id="mainContent" name="mainContent" tabindex="-1">2</a>
  <div style="padding-left:5px"></div>
</div>
<div id="DeltaPlaceHolderMain">
  <a id="mainContent" name="mainContent" tabindex="-1">3</a>
  <div style="padding-left:5px"></div>
</div>
<div id="DeltaPlaceHolderMain2">
  <a id="mainContent" name="mainContent" tabindex="-1">4</a>
  <div style="padding-left:5px"></div>
</div>
<div id="DeltaPlaceHolderMain2">
  <a id="mainContent" name="mainContent" tabindex="-1">5</a>
  <div style="padding-left:5px"></div>
</div>

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

IDs have to be unique!! Change them to classes, or else you'll have an invalid HTML.

After you've converted them to a class, you can do

$('.DeltaPlaceHolder').eq(1); // eq takes an element at the given index and 1 is second

For changing it into class, just replace id with class

Upvotes: 1

Related Questions