0

there is a div present in my js file

<div id="myid" data="mydata"></div>

when i try to access custom attribute data with pure javascript

var data  =  document.getElementById('myid').getAttribute('data');

jquery alone

 var data = $("#"+myid).attr('data');

above both mwthods are working properly but when i try to used the both jquery and javascript

var data = $("#"+myid).getAtrribute("data");

then is is giving error? but didn't able to get the reason ? can anyone explain please?

4
  • 2
    Really, you're suprised it doesn't work when you use a native javascript method on a jQuery object? Why would you even do that ? Commented Jan 13, 2015 at 8:19
  • i know its not appropriate but i was just keen to know the reason why this is not working. Commented Jan 13, 2015 at 8:22
  • 1
    FYI even completly unrelevant to issue, data isn't valid attribute for DIV element Commented Jan 13, 2015 at 8:23
  • It's not working because a jQuery object has no getAttribute property, it has it's own set of properties and methods, that are not at all related to what properties and methods a native DOM node would have. Commented Jan 13, 2015 at 8:27

3 Answers 3

4

You are applying a dom method to a jquery object which causes error instead jquery has a method to convert the selector to the dom element .get():

$("#"+myid).get(0).getAtrribute("data");

alert($('#myid').get(0).getAttribute('data'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myid" data="mydata"></div>

As you are using a data attribute then better to use data-* attribute and jQuery has a method to get it with .data() method:

<div id="myid" data-mydata="CustomisedData"></div>

then in the jQuery:

$('#myid').data('mydata'); // will give you "CustomisedData"
Sign up to request clarification or add additional context in comments.

Comments

1

Because $("#"+myid) is a jQuery instance, not HTML Element object. So you can't use DOM methods on some arbitrary object.

jQuery instance object is an array-like collection of DOM elements. It means that you can extract individual DOM element from it by index if you really need. So in your case you could do this:

$("#" + myid)[0].getAtrribute("data");

jQuery also offers dedicated method for it $.fn.get:

$("#" + myid).get(0).getAtrribute("data");

Comments

0

This should work:

var data = $("#"+myid)[0].getAtrribute("data");

Because to use javascript code, you need to use DOM object but jQuery uses array-like collection object.

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.