What is better 'parent()' or 'parents()'?
What is the better way to get a parent node for the following example of code?
...
<tr>
<td>
<table>
<tr>
<td>
<div class="blo开发者_如何学JAVAck_data">
Hello world!!
</div>
</td>
</tr>
</table>
</td>
</tr>
/*Javascript code 1*/
$('.block_data').parents('tr').first()...
/*Javascript code 2*/
$('.block_data').parent().parent()...
Which of the two codes is faster (considering perfomance, not coding)? Imagine a situation like that, with a lot of parents:
...
<tr>
<td>
...
</td>
</tr>
...
<tr>
<td>
<div>
<div>
<div>
<div class="block_data">
Hello world!!
</div>
</div>
</div>
</div>
</td>
</tr>
Since neither one of them actually work correctly for your desired functionality, the question of which method is faster is sort of beside the point, don't you think? You are looking for closest()
, not parent()
or parents()
. In general, it's probably a bad idea to think about performance until you are positive you have a method which works correctly.
Your use of
.parents('tr').first()
will withstand changes to the DOM where the element with the handler becomes more deeply nested.
In that case, I'd prefer to use
.parents('tr:first')
Another answer mentioned closest('tr')
. It is really a tossup between the two.
Some like using .parents()
because its name is more descriptive of what it is doing. But you need to be aware that it will return more than one result if there are multiple matches. That's where you need .first()
or :first
to get just the first one.
Between .closest()
and .parents()
, performance varies based on browser. I found in some quick tests that IE likes .parents()
better, while FF and Webkit like .closest()
better.
In my opinion it is better to use parents()
because in case your code changed you would refer to completely other element. It is bit slower thought, but you've got just few nodes there so it should't be much of the impact.
It is better to use parents()
and find the element you need than (in some other case) to write many .parent().parent().parent().parent().parent().parent().parent().parent()
. Code is more maintainable that way, imho.
精彩评论