<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
Why doesn't the above work, and how should I do this?
<div id="test"></div>
<script>
$(document).ready(function() {
alert($('#test').id);
});
</script>
Why doesn't the above work, and how should I do this?
Well, seems there has not been a solution and would like to propose my own solution that is an expansion of the JQuery prototype's. I put this in a Helper file that is loaded after the JQuery library, hence the check for
window.jQuery
It may not be perfect but it is a start to maybe getting inclusion into the JQuery library.
Returns either a single string value or an Array of string values. The Array of string values, is for the event an multi-element selector was used.
This is an old question, but as of 2015 this may actually work:
And you can also make assignments:
As long as you define the following JQuery plugin:
Interestingly, if
element
is a DOM element, then:.id
is not a valid jquery function. You need to use the.attr()
function to access attributes an element possesses. You can use.attr()
to both change an attribute value by specifying two parameters, or get the value by specifying one.http://api.jquery.com/attr/
Using above code you can get id.
id
is a property of an htmlElement
. However, when you write$("#something")
, it returns a jQuery object that wraps the matching DOM element(s). To get the first matching DOM element back, callget(0)
On this native element, you can call id, or any other native DOM property or function.
That's the reason why
id
isn't working in your code.Alternatively, use jQuery's
attr
method as other answers suggest to get theid
attribute of the first matching element.