Rooster Rooster - 1 year ago 43
jQuery Question

More efficient way to do parent().parent().parent() etc. in jquery

In this script I'm writing, I find myself using .parent() up to seven times in a row to get elements. While this works, it seems like there could/should be an easier way to do this/ function I'm unaware of. Any ideas other than more specific classes/ids on more elements?

Basically, my question boils down to accessing the div with id

when I have a reference to the span with id 'innerSpan' in the html below:

<div id='outer'>
<a href="some_url">
<span id="inner">bla bla</span>

So currently, I would do something like this:

var outer = $('#inner').parent().parent()

and that gets crazy with deeply nested elements.

Another example:

Here my html:

<div id="options_right">
<table id="product_options_list" class="table table-bordered">

<tbody id="1">
<select name="option_1_val[0]" class="option_table_select">
<option value="Red">Red</option>
<option value="Blue">Blue</option>
<option value="Green">Green</option>
<table class="table sub_options" id="0">
<select name="option_1_sub[0][]" class="option_table_select sub_option_select">
<option value="">None</option>
<option value="2">Size</option>
<div class="sub_option_value_holder">
<select name="option_1_sub_val[0][]" class="sub_option_values" style="display:none;"></select>
<a href="#" class="remove_sub_option btn btn-primary">Remove</a>
<a href="#" class="add_sub_option btn btn-primary">Add Another</a>

and my script. i wrote a function and need to pass it the ids of the main rows tbody as well as the secondary tables id so i can dynamically add more rows. You don't really need that function for this question but basically i get those ids like so:

get_suboption_row($(this).parent().parent().parent().parent().parent().parent().parent().attr('id'), $(this).parent().parent().parent().parent().attr('id'));



click the add another to trigger event

Answer Source

You have 2 nested tables,
to get what you want you can use this two DOM traversal methods .closest() or .parents():



jsFiddle demo

And just after a second look: numeric IDs are valid only in HTML5.