0

I want to identify each element by it's name attribute. Each element has the same class and will ultimately contain differing dynamic information.

For example I would want the following code to alert the individual element's name value:

html:

<p class="pexample" name="0">this is p #1</p>
<p class="pexample" name="1">this is p #2</p>
<p class="pexample" name="2">this is p #3</p>

jquery:

$('p').on('click', function() {
    if ($('p').attr('name') !== undefined) {
        alert($('p').attr('name'));
    }
})

Here is a jsfiddle.. http://jsfiddle.net/XG7nd/1/

This code however only alerts the initial elements name value. Help is greatly appreciated.

captainrad
  • 3,760
  • 16
  • 41
  • 74
  • I think you want `if ($(this).attr('name')` instead of `$('p')`. The latter selects all the `p` elements on the page... – crush Jun 27 '13 at 19:22

5 Answers5

6

This should do:

$('p').on('click', function() {
   var name = $(this).attr('name');// `this` here refers to the current p you clicked on
   if (name ) {
        alert(name); 
    }
})

While doing $('p').attr('name') this will always give you the name of the first item in the collection.

Demo

PSL
  • 123,204
  • 21
  • 253
  • 243
0

Try this:

$(document).on('click','p', function() {
    alert($(this).attr('name'));
});

DEMO

Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
0

You want to use $(this)

$('p').on('click', function() {
    if($(this).attr('name') !== 'undefined') {
        alert($(this).attr('name'));
    }
});
Jedediah
  • 1,916
  • 16
  • 32
0

This is occurring because you are getting the name attribute for the first <p> on every click. You need to specify the one that the event originated from:

$('p').on('click', function() {
if ($(this).attr('name') !== undefined) {
    alert($(this).attr('name'));
}
})

Note, jQuery selectors return an array of matching elements. You must use the this keyword to get a handle on the element in the current context.

FIDDLE

ExceptionLimeCat
  • 6,191
  • 6
  • 44
  • 77
0

Explanation

You keep looking for the p element even on click, so it'll select the first one it finds.

What your code says:

When p is clicked:

  • Find a p element and alert its attribute.

What you really want:

When p is clicked:

  • alert the clicked element's attribute

Solution

Select the attribute of this, which is the clicked element.

JSFiddle

JavaScript

$('p').on('click', function() {
    if ($(this).attr('name') !== undefined) {
        alert($(this).attr('name'));
    }
})

Read more about the this keyword.

Community
  • 1
  • 1
Jeff Noel
  • 7,500
  • 4
  • 40
  • 66