Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first sibling

Tags:

I'm trying to select the inner value of the first sibling - using jQuery - in an environment where I cannot alter the html markup.

I have the following:

<tr>     <td>3</td>     <td>bob</td>     <td>smith</td>     <td>[email protected]</td>     <td>         <img src="bobsmith.png" onclick="doSomething()" />     </td> </tr> 

I'm trying to get the value of the first <td> with the following:

function doSomething() {     var temp = $(this).parent().parent().children().filter(':first');     alert("you clicked person #" + temp.html()); } 

All I get from this is null.

I've tried various combinations with with the .siblings() function too, but to no avail.

Any ideas?

Thanks,

Note: I forgot to mention that the table the excerpt is from is dynamically loaded & refreshed from an ajax call. This may be pertinent for suggestions that include binds.

Solution: I've gone with the following solution, inspired by the accepted answer:

<tr>     <td>3</td>     <td>bob</td>     <td>smith</td>     <td>[email protected]</td>     <td>         <img src="bobsmith.png" onclick="doSomething(this)" />     </td> </tr> 

and for the jQuery javascript:

function startStopNode(el) {     var temp = $(el).parent().siblings(':first').html();     alert("you clicked: " + temp); } 
like image 711
Mike Avatar asked Jan 27 '10 11:01

Mike


People also ask

How do I target my first sibling in CSS?

The adjacent sibling combinator ( + ) separates two selectors and matches the second element only if it immediately follows the first element, and both are children of the same parent element .

What is general sibling selector?

The general sibling selector (~) selects all elements that are next siblings of a specified element.

Is used to select adjacent sibling of an element?

The CSS adjacent sibling selector is used to select the adjacent sibling of an element. It is used to select only those elements which immediately follow the first selector.


2 Answers

$( 'td:first-child', $( this ).parents ( 'tr' ) ).html (); 

This will select the first TD element (:first-child filter) in the parent TR of the image. parents() returns all parents of the element, and we filter the parents so that only TR elements are returned.

Also try writing your image like so:

<img src="bobsmith.png" onclick="doSomething(this)" /> 

and your function like so:

function doSomething ( imgEl ) { } 

and use imgEl instead of this

like image 76
Jan Hančič Avatar answered Oct 02 '22 11:10

Jan Hančič


$('tr td:last-child img').click(function(){      alert($('td:first-child',$(this).closest('tr')).text());  }); 
like image 37
Reigel Avatar answered Oct 02 '22 11:10

Reigel