Skip to content Skip to sidebar Skip to footer

How Can I Get Id,class Or Name Attr An Element With Jquery

I'm new in jquery. How can I get name,ID or class name an element with jquery.I'm trying as;

Solution 1:

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

<divclass="className"onclick="getname();"></div><divid="idName"onclick="getName();"></div><divname="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.

Solution 2:

Firstly using jQuery you should attach click() handlers rather than use antiquated onclick attributes. Then you can use the this keyword in the manner you have in your function.

Try this:

<divclass="className"></div><divid="idName"></div><divname="attrName"></div>
$(function() {
    $("div").click(function() {
        var name = this.name;
        var cls = this.className;
        var id= this.id;

        alert("Name: " + name + " / Class: " + cls + " / Id: " + id);
    });
});

Example fiddle

The attributes you've selected are all available through POJS, you could also convert this to a jQuery object to get other attributes, for example:

var title = $(this).attr('title');
var myattribute = $(this).data('myattribute'); // using HTML5: <div data-myattribute="foo"></div>

Solution 3:

You need to pass a reference to the element you want to get the name attribute of. Try this:

jQuery

functiongetName(me) {
    attrName = $(me).attr("name");
    alert(attrName);
}​

HTML

<divclass="className"onclick="getname(this);">a</div><divid="idName"onclick="getName(this);">b</div><divname="attrName"onclick="getName(this)">c</div>

jsFiddle example

Now you should get the name of the last element since that's the only element that has a name. The others will return undefined.

Post a Comment for "How Can I Get Id,class Or Name Attr An Element With Jquery"