Wednesday, 15 June 2011

javascript - Get image src using jQuery -



javascript - Get image src using jQuery -

i'm trying src attribute of html image. seems can find img element in dom src attribute undefined, ideas why?

html:

<table id="combotable" style="width: 100%; height: 100%; margin-bottom: 10px;" data-bind="click: $root.selectcombo"> <tr> <td> <img class="selector" src="~/images/roundoffbutton.png" style="position: absolute;margin-left: -57px; margin-top: -35px;" /> </td> <td style="height: 35px;"> <table style="width: 100%; background-color: #0097d8;padding:5px;"> <tr style="padding:5px;"> <td style="height: 36px; padding-left: 14px; font-weight: bold;color: black; margin: 1px; width: 70%; text-align:left;"> <span data-bind="text: description" style="padding-left: 5px;" /> </td> <td style="width: 30%;padding:8px; text-align: center;color: white; background-color:black;"> <span data-bind="text: formatcurrency(price)" style="font-size: 14px; white-space: nowrap; font-weight: bold;" /> </td> </tr> </table> </td> </tr> </table>

javascript:

var combospan = $("span:contains('" + description + "')"); var img = $(combospan).closest(".selector"); alert('image object - ' + img); var src = $(img).attr('src'); alert(src); //src undefined

working demo

use valid selector img, img , span have different parent, can't utilize closest() straight in case.

also combospan,img jquery objects. don't need $(combospan)

use .closest('#combotable') hierarcy has table within table.

<table> <tr> <td> <img> //you need this. </td> <td> <table> <tr> <td> <span> //you have this. </td> </tr> </table> </td> </tr> </table>

final code:

var combospan = $("span:contains('" + description + "')"); var img = combospan.closest('#combotable').find('.selector'); //change line alert('image object - ' + img); var src = img.attr('src'); alert(src); //src undefined

javascript jquery html html5

No comments:

Post a Comment