How to get an attribute of several "tags" with same ID

7

Hello, when I click on one of the 3 options in "HTML" that is in the code below, I want the function in "JS" to issue an "alert" with the "idPost" in which it was clicked. EX: When I click on the link "PHP" it issues an alert 25, which would be its idPost. But when I click on the other options the function does not emit any alerts. If I did other two functions and changed the ids, I know it would work, but since it is a post system, that would be my options, when adding a new post I would have to do another new function, so I used the same ids. I hope it has been made clear!

HTML code:

<p id="linkPost" idPost="25"><a href="#">PHP</a></p>
<p id="linkPost" idPost="26"><a href="#">HTML</a></p>
<p id="linkPost" idPost="27"><a href="#">JAVASCRIPT</a></p> 

JS Code:

$('#linkPost').on('click', function(){
     var id = $(this).attr('idPost');
     alert(id);
});
    
asked by anonymous 22.04.2015 / 01:52

2 answers

8

Double ID's is HTML invalid. Uses classes instead of id.

You can change the HTML to

<p class="linkPost" idPost="25"><a href="#">PHP</a></p>
<p class="linkPost" idPost="26"><a href="#">HTML</a></p>
<p class="linkPost" idPost="27"><a href="#">JAVASCRIPT</a></p> 

and change only the selector from # to . , keeping the rest of your code as is. That is:

$('.linkPost').on('click', function(){

jsFiddle: link

Or you can use $('[idPost]') selector, which uses this attribute in the search instead of classes or ids. In this case it would be:

$('[idPost]').on('click', function(){

jsFiddle: link

    
22.04.2015 / 09:14
6

When you click, you click on the element a , so your selector can be changed to $('#linkPost a') . With this we can get #linkPost using the parent() function, since a is #linkPost .

It is very important that you realize that HTML is invalid, as it is not allowed to use elements with the same ID. Instead, you can use classes for elements with repeated properties. Thus, the selector changes to $('.linkPost a') :

$('.linkPost a').on('click', function(){
     var id = $(this).parent().attr('idPost');
     alert(id);
});

Fiddle: link

    
22.04.2015 / 02:35