Reputation: 15303
I am trying to get a attribute value from my dom element, but i am getting result as:
Uncaught TypeError: Object #<HTMLDivElement> has no method 'attr'
I am not able to get the attribute value at all.. what is the issue..?
here my my code :
HTML:
<div class="label" aria-label="Logo">
<div class="trunc-string">
<div class="start denali-tooltip tooltip-on-truncate"><span>Logo</span></div>
</div>
</div>
jQuery:
var x = $("div.label")[0];
console.log (x.attr("aria-label"));
any one direct me in the right way please..?
Upvotes: 3
Views: 8482
Reputation: 816422
By default, .attr
will return the attribute value of the first selected element, if used as getter:
Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
So all you really have to do is
$("div.label").attr("aria-label");
If you want to filter selection to only include the first element (because you want to use it somewhere else), you can use .first
:
var x = $("div.label").first();
or .eq(0)
:
var x = $("div.label").eq(0);
The reason why you get the error is that $(...)[i]
returns the selected DOM element at that position. DOM elements don't have an .attr
method.
Upvotes: 1
Reputation: 7332
if you multiple div.label
element and you want to get value according to its node position, You can go with
var x = $("div.label:eq(0)");
console.log (x.attr("aria-label"));
Otherwise if there is only one div.label
element, You can go with
var x = $("div.label");
console.log (x.attr("aria-label"));
Upvotes: 1
Reputation: 10378
var x = $("div.label")[0];
//^^^^^ by this you get a object with html of .label
console.log ($(x).attr("aria-label"));
//^^^^^^^^^^^^^^then use as a jquery object and apply their method
Upvotes: 1
Reputation: 10896
try something like this,
$(function(){
// will give you pure javascript(DOM) object,so use getAttribute().
var x = $("div.label")[0];
console.log(x.getAttribute("aria-label"));
//using jquery
console.log($(x).attr("aria-label"));
})
Upvotes: 2
Reputation: 2375
var x = $("div.label:eq(0)");
console.log (x.attr("aria-label"));
Upvotes: 1
Reputation: 20418
Try this
var x = $("div.label"); //or $("div.label:eq(0)")
console.log (x.attr("aria-label"));
Upvotes: 1
Reputation: 15699
It should be $("div.label:eq(0)");
instead of $("div.label")[0];
var x = $("div.label:eq(0)");
Upvotes: 1