0

I have same ids for different elements. like below

$("name").val();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="name">test 0</div>
    <div id="name">test 1</div>
    <div id="name">test 2</div>

Using jQuery how to get test 1 onclick of element in console.

I am trying for a production site for web analytics tracking purpose.

Kartheek Sarabu
  • 3,886
  • 8
  • 33
  • 66
  • 3
    The problem is moot as ***you cannot have multiple `id` elements with the same value*** in the DOM. Use classes instead, then the `this` keyword can be used within the jQuery `click` handler to reference the element. – Rory McCrossan May 23 '18 at 09:55
  • This is in production so we cannot change now. @RoryMcCrossan – Kartheek Sarabu May 23 '18 at 09:56
  • 1
    That's even *more* reason to change it IMO - you have broken logic in a live system. – Rory McCrossan May 23 '18 at 09:56
  • id .. identifier .. how can you indentify a singular element by a unique string when all of them share that value? You should have used classes if you wanted multiple elements sharing same functionality/css. ID's are strictly unique. – treyBake May 23 '18 at 09:59
  • a dirty hack would be to use an attribute selector but I would recommend fixing this as invalid code causes other issues like lower seo rankings and failed accessibility tests (apparently you are able to be prosecuted in europe if your site doesn't reach single a standard but I have yet to see this happen) – Pete May 23 '18 at 10:24
  • This website is in live/production. For analytics purpose I need click events. I cant change the existing element ids – Kartheek Sarabu May 24 '18 at 04:50

3 Answers3

0

Can multiple different HTML elements have the same ID if they're different elements?
Use class instead:

<div class="name1">A</div>
<div class="name1">B</div>
<div class="name2">C</div>

And then use jQuery's class selector, which matches the CSS syntax:

$('.name1')
0

you can not give same id, if we give same id to different element then it will result in error, Id must be unique. Hence we can use class name,which can be used multiple times. So i suggest you to use class name instead of id.

<div class="name1" id="name11">A</div>
<div class="name1" id="name12">B</div>
<div class="name1" id="name13">C</div>
0

change id's to class:

<div class="my-div" id="test-1">content</div>
<div class="my-div" id="test-2">content 2</div>
<div class="my-div" id="test-3">content 3</div>

an ID is a DOM element identifier and can't be duplicated, or else what's the point of an ID?

A class is more generic and can be applicable to multiple elements.

To get in jQuery we do:

$('.my-div').on('click', function()
{
    console.log($(this));
});

by using $(this) we get the clicked object, and doing things like:

$(this).attr('id') or $(this).html() will return the id/html according to the clicked div with matching class my-div

treyBake
  • 6,440
  • 6
  • 26
  • 57