开发者

Selecting a descendant in jQuery if I have a reference to an item already

开发者 https://www.devze.com 2023-01-28 19:47 出处:网络
I have the following HTML: <table id=\"myTable\"&g开发者_运维知识库t; <tr> <td><div>test</div></td>

I have the following HTML:

<table id="myTable"&g开发者_运维知识库t;
  <tr>
    <td><div>test</div></td>
  </tr>
  <tr>
    <td><div>test</div></td>
  </tr>
</table>

I have a reference to #myTable in the variable $myTable.

How can I select all descendant div tags without using the string #myTable again (i.e. use the $myTable object only)?

To clarify, assuming this example worked:

$('#myTable div')

... it fails to meet my criteria, since I don't want to retype #myTable.

Additionally, I'd prefer not having to specify each parent in the hierarchy like this:

$myTable.children('tr').children('td').children('div')

I tried using

$myTable.children('div')

... but it seems to only select immediate children, which the div elements are not.

I want to use something terse like this:

$myTable.descendants('div')


You can use the find function in jQuery.

$myTable.find('div');

Alternatively you can specify the scope like this:

$('div', $myTable);

both should return the same set


The find function does exactly what you want.

$myTable.find('div');


You might have trouble testing the suggested solutions because you have included the "#" in your id attribute. It should be:

<table id="myTable">

And you can just use $('div', $myTable) to select the descendant divs.

Check out solution here

0

精彩评论

暂无评论...
验证码 换一张
取 消