Why doesn\'
Since the id is an attribute, you can get it by using the attr
method.
This is an old question, but as of 2015 this may actually work:
$('#test').id;
And you can also make assignments:
$('#test').id = "abc";
As long as you define the following JQuery plugin:
Object.defineProperty($.fn, 'id', {
get: function () { return this.attr("id"); },
set: function (newValue) { this.attr("id", newValue); }
});
Interestingly, if element
is a DOM element, then:
element.id === $(element).id; // Is true!
If you want to get an ID of an element, let's say by a class selector, when an event (in this case click event) was fired on that specific element, then the following will do the job:
$('.your-selector').click(function(){
var id = $(this).attr('id');
});
The jQuery way:
$('#test').attr('id')
In your example:
$(document).ready(function() {
console.log($('#test').attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div>
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')
which is different from .attr()
and $('#test').prop('foo')
grabs the specified DOM foo
property, while $('#test').attr('foo')
grabs the specified HTML foo
attribute and you can find more details about differences here.
Maybe useful for others that find this thread. The code below will only work if you already use jQuery. The function returns always an identifier. If the element doesn't have an identifier the function generates the identifier and append this to the element.
var generatedIdCounter = 0;
$.fn.id = function() {
var identifier = this.attr('id');
if(!identifier) {
generatedIdCounter++;
identifier = 'isGenerated_' + generatedIdCounter;
this.attr('id', identifier);
}
return identifier;
}
How to use:
$('.classname').id();
$('#elementId').id();
$('tagname').attr('id');
Using above code you can get id.