Carlota
Carlota

Reputation: 1237

jQuery - how to find a table inside a div

I have the following jsp

<div class="content" id="divContent">
    <ul class="ul-content ui-sortable" id="content" style="padding-left: 10px; max-width: 920px;">
        <li class="draggable freetext ui-draggable ui-draggable-handle content-element" style="width:; height:; overflow: auto;">
            <div class="element-content">
                <div class="questiontitle elementtitle" id="58f95b7f-c127-7e40-a3a7-5253ed32fc31">
                    <table>
                        <tbody>
                            <tr>
                                <td>
                                    <span class="optional1">(Opcional  )</span>
                                </td>
                                <td>New Freetext Question</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <input class="freetext" type="text" readonly="readonly">
                <div class="questionhelp">
                </div>
            </div>
        </li>
    </ul>
</div>

I want to find the table inside the div

<div class="questiontitle elementtitle" id="58f95b7f-c127-7e40-a3a7-5253ed32fc31">

I wrote the code:

var contentDivTable = $(contentDiv).find('tr');
var numerocontentDivTable = contentDivTable.length;
console.log('additem after addfreetext contenDiv  number table ',numerocontentDivTable);

This is the trace in browser's console

additem after addfreetext contenDiv  [object HTMLDivElement]
"additem after addfreetext contenDiv "
<div class="questiontitle elementtitle" id="146b750d-18e8-b8a5-a34d-082c9bd04e0d">New Freetext Question</div>
additem after addfreetext contenDiv  number table  0

How can I get the element table?

Upvotes: 6

Views: 34291

Answers (3)

Satinder singh
Satinder singh

Reputation: 10198

If divContent have single .questiontitle class div, then you can try as below

var tbl= $("#divContent  .questiontitle").find('table');

// this will display full table html content
console.log(tbl.html());

Then if you want to loop over table row data try below code

$(tbl).find('tr').each(function(){
    var currentRow=$(this);
    var col1_value=currentRow.find("td:eq(0)").text();
    var col2_value=currentRow.find("td:eq(1)").text();
 });

Upvotes: 0

Robert Williams
Robert Williams

Reputation: 1410

If you want to select the table inside a div

  1. Apply a css class on div like: <div class="content">
  2. Then use $('.content table') to select table which is inside that div

Upvotes: 5

Milan Chheda
Milan Chheda

Reputation: 8249

If you want to check whether there is a table or not, you can do:

if($("#divContent").find('table').length) {
 // table exists
} else {
 // no table found
}

Upvotes: 2

Related Questions