3

I am having trouble getting an ID of an element. The codes work in FF and chrome but not IE. Can anyone help me about it? Thanks a lot

<td id='tdID'>
    <img id='test' src='a.jpg' class='imgClass' />
</td>

jquery

$('.imgClass').click(function(){
   ip=$(this).parent().attr('id');          

   //undefined in IE
   console.log(ip);
})
wirey00
  • 33,517
  • 7
  • 54
  • 65
FlyingCat
  • 14,036
  • 36
  • 119
  • 198

2 Answers2

2

<td>s must be inside a <table>. If they are not, most browsers will remove them from the DOM. So, the $(this).parent() might not be the element you think.

Here's a quick demo: http://jsfiddle.net/NTICompass/cyK3h/

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
1

Use prop, not attr

$('.imgClass').on("click", function(){
   var id = $(this).parent().prop("id");          
   console.log(id);
});

also in case you change the markup it might be safer to use closest

$('.imgClass').on("click", function(){
   var id = $(this).closest("td").prop("id");          
   console.log(id);
});

jsFiddle

epascarello
  • 204,599
  • 20
  • 195
  • 236