0

I have a jquery plugin that uploads the selected photo using ajax and php.

It works fine but i need to pass the attribute of the selected photo to php. I recieve the html element in $(this)[0]. I need something like:

$(this)[0].attr("data-index");

What is the proper way of getting attr from $(this)[0]

2
  • 2
    $(this).eq(0).attr("data-index") or $($(this)[0]).attr("data-index"); Commented Feb 20, 2016 at 5:12
  • 1
    If you don't want to wrap the element again in jquery wrapper then you can use javascript approach $(this)[0].getAttribute("data-index"); Commented Feb 20, 2016 at 5:18

2 Answers 2

1

You have to select the element like

$($(this))

Then you can find the attribute

So your code should look like

$($(this)[0]).attr("data-index");
Sign up to request clarification or add additional context in comments.

4 Comments

@webarch - This is needlessly inefficient. $(this).attr("data-index"); is all that is needed. There's no need for the double nested jQuery objects or for the [0] here.
@jfriend00 Yes. You are right. I thaught he was getting that from an array. I will update it
@RinoRaj i'm getting that from an array, so your first answer was correct
@WebArch Reverted back to old one.
0

In jQuery, you can do this:

$(this).data("index");

which will automatically access the data-index attribute using jQuery's .data() feature.

Or you can use this to read the attribute directly:

$(this).attr("data-index");

Since, you know there's only one element in the jQuery object, there's no reason to use the [0] complication. Though you don't need it here, if you ever want the first item out of a jQuery object and you want the result in a jQuery object, you can use .eq(0) as in $(this).eq(0).attr("data-index");, but since you already know there's only one element in $(this), there's no reason for it here.


Or, in plain JS, you can do this:

this.getAttribute("data-index");

Or, in modern browsers, you can do:

this.dataset.index

which uses the newer .dataset feature.

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.