How can I get the ID of an element using jQuery

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

<div id="test"></div>

$(document).ready(function() {
    alert($( #test ).id);
});  

Why doesn t the above work, and how should I do this?

Answers

The jQuery way:

$( #test ).attr( id )

In your example:

<div id="test"></div>

$(document).ready(function() {
    alert($( #test ).attr( id ));
}); 

Or through the DOM:

$( #test ).get(0).id;

or even :

$( #test )[0].id;

and reason behind usage of $( #test ).get(0) in JQuery or even $( #test )[0] is that $( #test ) is a JQuery selector and returns an array() of results not a single element by its default functionality

an alternative for DOM selector in jquery is

$( #test ).prop( id )

http://stackoverflow.com/questions/5874652/prop-vs-attr http://stackoverflow.com/questions/5874652/prop-vs-attr

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/3239598/how-can-i-get-the-id-of-an-element-using-jquery

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils