Dilip Kanogiya Dilip Kanogiya - 10 months ago 57
jQuery Question

How to find element id based on data-index attributes

I am working on a project and I am having problem on finding element id based on the custom attributes (data-index). Plz someone help me...


<div id="2" data-index="1" style="width: 500px; left: -500px; transition-duration: 0ms; transform: translate(500px, 0px) translateZ(0px);"><b>May your birthday and every day be filled with the warmth of sunshine, the happiness of smiles, the sounds of laughter, the feeling of love and the sharing of good cheer.</b></div>

JS Function:

function saveLike(){
var currentPostion = mySwipe.getPos();
var cars = $("div").find("[data-index='" + currentPostion + "']").id;
str = JSON.stringify(cars);



find selects descendants of an element. You should use the filter method.

Also for getting the id you should either select an element from the collection:

$("div").filter("[data-index='" + currentPostion + "']")[0].id;

or use the prop or attr method. jQuery collections do no have id property.

$("div").filter("[data-index='" + currentPostion + "']").prop('id');