Can't manage to target an element in jQuery

  • A+
Category:Languages

I'm trying to target a parent from a link with a jQuery function, at first to get its innerHtml but now, just to get its value.

However, I can't manage to track it and I've been putting way too much time on this simple problem.

Here's my html :

<table>   <tr>       <td title="td_title_1" value="td_value_1">Some text<a href="#" title="Copy">Element_1</a></td>       <td title="td_title_2" value="td_value_2">Some other text<a href="#" title="Copy">Element_2</a></td>   </tr> </table> 

And my jQuery:

$(function(){     $("*").on('click','a[title="Copy"]',function(){         var clipboard = $(this).parent('td').find('[title="td_title1"]').val();         alert(clipboard);     }); }); 

I tried parent(), parents(), closest()... I'm still getting "undefined" value. And yeah, the jQuery lib is added.

Also, how would you get the "Some text" part?

Thanks for your time.

 


The first thing is you need to use stopPropagation() so that it works only for the element you desire and the next thing is you can use the simple way to clone the element so that you get only the text part of <td> element that is the immediate parent of the clicked element.

$(function() {   $("*").on('click', 'a[title="Copy"]', function(e) {     var clipboard = $(this).parent('td')       .clone() //clone the element       .children() //select all the children       .remove() //remove all the children       .end() //again go back to selected element       .text();     alert(clipboard);     e.stopPropagation();   }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table>   <tr>     <td title="td_title_1" value="td_value_1">Some text<a href="#" title="Copy">Element_1</a></td>     <td title="td_title_2" value="td_value_2">Some other text<a href="#" title="Copy">Element_2</a></td>   </tr> </table>

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: