How can I get id,class or name attr an element with jquery

attr, html, jquery

Solution

Try this:

JavaScript

$(function () {
    $('div').click(function () {
        var elem = $(this);
        alert('Class: ' + elem.attr('class'));
        alert('Id: ' + elem.attr('id'));
        alert('Name: ' + elem.attr('name'));    
    });​​​​
});

HTML

<div class="className" onclick="getname();"></div>
<div id="idName" onclick="getName();"></div>
<div name="attrName" onclick="getName()"></div>

CSS

​div {
    width: 100px;
    height: 100px;
    border: 1px solid black;
}​

JSfiddle: http://jsfiddle.net/54ynV/

In the script above we're attaching to the click event of every div on the page `$('div').click...`. In the callback we're getting it's attributes.

Problem

I'm new in jquery. How can I get name,ID or class name an element with jquery.I'm trying as; ``` <div class="className" onclick="getname();"></div> <div id="idName" onclick="getName();"></div> <div name="attrName" onclick="getName()"></div> function getName(){ attrName = $(this).attr("name"); alert(attrName); } ``` but doesn't work

Original source