Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

jquery

attr

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

like image 377
regxcode Avatar asked Jan 16 '23 00:01

regxcode


2 Answers

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.

like image 81
Minko Gechev Avatar answered Jan 17 '23 16:01

Minko Gechev


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:

<div class="className"></div>
<div id="idName"></div>
<div name="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>
like image 22
Rory McCrossan Avatar answered Jan 17 '23 17:01

Rory McCrossan