-2

How can I get the id of a "div" tag that contains certain daata attributes , Here's what am trying to do

 var $element = $("div[data-price='"+price_1+"'][data-capacity='"+capacity_1+"'][data-debit='"+debit_3+"']").data('id');
        alert('id is '+ $element);

And the div tag is :

<div class="sh_content" id="sh_content_3" data-price="price_1" data-capacity="capacity_1" data-debit="debit_3">
<!-- Content --->
</div>
<div class="sh_content" id="sh_content_2" data-price="price_1" data-capacity="capacity_2" data-debit="debit_2">
    <!-- Content --->
    </div>

Any ideas about what i'm doing wrong ?

Ayman P.
  • 3
  • 7

1 Answers1

1

You're using .data() when you're trying to get the id, and that won't work. The correct API is .prop():

var $element = $("div[data-price='"+price_1+"'][data-capacity='"+capacity_1+"'][data-debit='"+debit_3+"']")
  .prop('id');
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • @AymanP. then that probably means there is no element with the requested attribute values. – Pointy Dec 21 '16 at 14:25
  • ,when I do " var $element = $("div[data-price='"+price_+"'][data-capacity='"+capacity_+"'][data-debit='"+debit_+"']").addClass('example');" It works, but when retrieving the id , it doesn't – Ayman P. Dec 21 '16 at 14:28
  • @AymanP. it's not possible for me to help without seeing more of your **actual** code. Try setting up a CodePen or jsfiddle. – Pointy Dec 21 '16 at 14:29
  • I was using some different data attributes value, .prop() workedfine , thank youu – Ayman P. just now edit – Ayman P. Dec 21 '16 at 14:51