Nahouto
Nahouto

Reputation: 1385

Really next element with specific class

I am newbie in Jquery, sorry for my silly question.

Here is my HTML code :

<tr role="row" class="odd">
   <td><input type="checkbox" class="mycheckbox" value="2166"></td>
   <td class="sorting_1">2166</td>
   <td><span class="myparentid">743</span>
   </td><td>0</td>
</tr>

I would like to jump from 'mycheckbox' element to 'myparentid' element, ignoring the tree structure. In Jquery, I tried something like :

var checkedRow = $(".mycheckbox");
var nextelem = checkedRow.next(".myparentid");

It does not work because next searches only in siblings...

Can you give me a hint ?

Thanks !

Upvotes: 0

Views: 46

Answers (1)

fdomn-m
fdomn-m

Reputation: 28611

The easiest option is to go up to a common parent element (in this case the table row), then back down to the one you want:

$(".mycheckbox").closest("tr").find(".myparentid")

Edit: To add some additional information:

$(".mycheckbox")

is the starting location, it's at: tr>td>input.mycheckbox

(where > means directly below in the html tree)

.closest moves up the tree until it finds a matching parent element, so .closest("tr") will find

<tr role="row" class="odd">

by looking at the direct parent "td", then it's direct parent "tr".

Normally I'd use a class here (<tr class="businessobjectcontainer">) (depending on what the business object is) then it can be a div or tr if you change this part of it later and seeing .odd I'd assume this is for styling and there'll be a .even - so that's not ideal as a selector. So "tr" would have to do.

.find() does the opposite of .closest and goes down the tree looking for a matching element, in this case .myparentid will find: tr>td>span.myparentid

which is what you're looking for.

.find() may not be the most efficient, but it's probably the most flexible as it means you can move the content of your tr around as much as you like.

A move efficient alternative might be to use:

$(">td>span.myparentid", $(".mycheckbox").closest("tr")) 

but mostly it's just changing the syntax.

Upvotes: 4

Related Questions