3gwebtrain
3gwebtrain

Reputation: 15303

Unable to get the attribute value using jquery method

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..?

Live Demo

Upvotes: 3

Views: 8482

Answers (7)

Felix Kling
Felix Kling

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

Prasanth K C
Prasanth K C

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.labelelement, You can go with

var x =  $("div.label");
console.log (x.attr("aria-label"));

Upvotes: 1

Rituraj ratan
Rituraj ratan

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

see demo

Upvotes: 1

rajesh kakawat
rajesh kakawat

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

Ankit Tyagi
Ankit Tyagi

Reputation: 2375

var x =  $("div.label:eq(0)");
console.log (x.attr("aria-label"));

Upvotes: 1

Sridhar R
Sridhar R

Reputation: 20418

Try this

var x =  $("div.label"); //or $("div.label:eq(0)")
console.log (x.attr("aria-label"));

Fiddle

Upvotes: 1

codingrose
codingrose

Reputation: 15699

It should be $("div.label:eq(0)"); instead of $("div.label")[0];

var x =  $("div.label:eq(0)");

Updated fiddle here.

Upvotes: 1

Related Questions