1

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

HTML CODE:

<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);
console.log(str);
alert(str);

}

3 Answers3

0

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');
Ram
  • 143,282
  • 16
  • 168
  • 197
0

//i'm assuming you're lookign for the id of that div. tested

$("div[data-index='1']").attr('id')
chungtinhlakho
  • 870
  • 10
  • 21
0

plese check below working code getting attribute value

function saveLike() {
  var currentPostion = 1;//mySwipe.getPos();
  var cars = $("div")[0].getAttribute('data-index');
  //find("[data-index='" + currentPostion + "']").id;
  str = JSON.stringify(cars);
  console.log(str);
  alert(str);
  return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<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>
<input type="button" value="save" name="save" onclick="return saveLike();">
navnit
  • 310
  • 3
  • 16