Getting IMG tag by traversing through html elements in jquery

时间:2015-05-12 22:24:13

标签: javascript jquery html css

How can I get the id value of the img tag using jquery? Once one of the divs with class containing polo.

this = line with **

Actions

Once one of the divs is clicked I want to traverse up through the elements and get the first elemwnt with and img tag. Then I want to alert the id of the img element.

<div style="width: 240px" class="outer">
   <img id="polo" class="apparelimage" src="images/Nike Polo - Navy.jpg" height="200px" width="200px" alt="" style="border: 1px solid black; cursor: pointer;">
   <br>
   <label style="font-size: small;"><b>COLORS</b></label>
   <div style="width: 280px; display: flex;">
      <div class="polo-black apparelimage" style="width: 30px; height: 30px; background-color: black; margin-right: 5px;"></div>
      <div class="polo-gray apparelimage" style="width: 30px; height: 30px; background-color: gray; margin-right: 5px;"></div>
      <div class="polo-lightblue apparelimage" style="width: 30px; height: 30px; background-color: lightblue; margin-right: 5px;"></div>
      <div class="polo-navy apparelimage" style="width: 30px; height: 30px; background-color: navy; margin-right: 5px;"></div>
      <div class="polo-white apparelimage" style="width: 30px; height: 30px; background-color: white; margin-right: 5px;"></div>
   </div>
</div>

3 个答案:

答案 0 :(得分:4)

The problem is that the \#import <</>googleplus-ios-sdk/GooglePlus.h</>> element is not a direct ancestor of the clicked <img> elements. But if you can add a class to the outermost div. you can then use .closest() to find it, and then use .find() to search back down.

<div>

Then you can use:

<div class="apparelContainer" style="width: 240px">
   <img ...

NOTE: The OP has changed the code in the question to reflect what is shown above.

Regarding the second issue, you need to get the $('.apparelimage').click(function () { var id = this.id; if (id == "") { alert($(this).closest('.apparelContainer').find('img.apparelimage').html()); } }); property from the DOM element, but you have a jQuery object.

Use either:

id

Or:

$(this).closest('.outer').find("img").attr('id')

jsfiddle

答案 1 :(得分:2)

try this .. this for divs id starts with polo

ini_set('display_errors', 1)

if you want id containing polo

$('[class^="polo"]').on('click',function(){
    $(this).parent().parent().find('img').attr('id');
});

DEMO HERE

答案 2 :(得分:-1)

Instead of SELECT COLUMNA, COLUMNB, COLUMNC AS [Column3] FROM TABLE1 UNION ALL SELECT COLUMNA, COLUMNB, COLUMND AS [Column3] FROM TABLE2 , try parent().find to traverse up.