3

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

0

7 Answers 7

2

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"));

        })
Sign up to request clarification or add additional context in comments.

2 Comments

"will give you pure javascript object" I think you mean "DOM element" instead. A jQuery object is also a "pure JavaScript object".
yes because jquery object is also one kind of javascript object
1

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

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

Updated fiddle here.

Comments

1

Try this

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

Fiddle

Comments

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

Comments

1
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

Comments

1

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"));

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.